springboot中操作redis

1.maven引入相关依赖

<dependencies>
 	<!-- spring-boot-starter-data-redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- commons-pool2 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.11.1</version>
        </dependency>
        <!--jackjson-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
</dependencies>

2.配置redis

application.yml

spring:
  # 配置redis
  redis:
    host: 192.168.***.***
    port: 6379
    password: ******
    lettuce:
      pool:
        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
        max-idle: 8 # 连接池中的最大空闲连接
        max-wait: 100 # 连接池最大阻塞等待时间(使用负值表示没有限制)
        min-idle: 0 # 连接池中的最小空闲连接
    database: 0 # redis数据库索引(默认为0)

3.配置序列化

package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * Redis  序列化方式配置
 *
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        // 创建RedisTemplate<String, Object>对象
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);
        // json方式序列化对象
        GenericJackson2JsonRedisSerializer jsonRedisSerializer =
                new GenericJackson2JsonRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(RedisSerializer.string());
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(RedisSerializer.string());
        // value序列化方式采用jackson
        template.setValueSerializer(jsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jsonRedisSerializer);
        return template;
    }

}

4.测试类中进行测试

package com.example;

import com.example.entity.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

@SpringBootTest
class SpringDataRedisTestApplicationTests {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 测试redis的String类型
     */
    @Test
    void testString() {
        redisTemplate.opsForValue().set("name", "minqiliang");
        System.out.println(redisTemplate.opsForValue().get("name"));
    }

    /**
     * 使用StringRedisTemplate操作redis(需要手动进行序列化和反序列化)
     * @throws JsonProcessingException
     */
    @Test
    void testString2() throws JsonProcessingException {
        // 创建一个对象
        User user = new User("001", "minqiliang", 18);
        // 由于StringRedisTemplate默认使用的是String的序列化器,所以这里需要将对象转换成json字符串
        String json = objectMapper.writeValueAsString(user);
        // 存入redis
        stringRedisTemplate.opsForValue().set("user:001", json);
        // 从redis中取出数据
        String s = stringRedisTemplate.opsForValue().get("user:001");
        // 将json字符串转换成对象
        User u = objectMapper.readValue(s, User.class);
        System.out.println(u);
    }

    @Test
    void testHash() {
        // 存入redis
        redisTemplate.opsForHash().put("user:002", "id", "002");
        redisTemplate.opsForHash().put("user:002", "name", "张三");
        redisTemplate.opsForHash().put("user:002", "age", 18);
        // 获取对应的key的所有值
        System.out.println(redisTemplate.opsForHash().entries("user:002"));
        System.out.println("====================================");
        // 获取对应的key的某个值
        System.out.println(redisTemplate.opsForHash().get("user:002", "id"));
        System.out.println(redisTemplate.opsForHash().get("user:002", "name"));
        System.out.println(redisTemplate.opsForHash().get("user:002", "age"));
    }
}

热门相关:峡谷正能量   法医娇宠,扑倒傲娇王爷      梦回大明春   我的嫂子