1. 程式人生 > 其它 >02 Springboot整合redis

02 Springboot整合redis

02 Springboot整合redis

RedisTemplate使用

專案的搭建

建立springboot專案哦

1 加入依賴

 <!-- spring boot redis快取引入 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- 快取連線池-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

        <!-- redis 儲存 json序列化 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
        </dependency>
		 <!-- 生成getset方法 -->
		 <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

2 實體類

/**
 * @author : look-word
 * @date : 2022-05-12 15:55
 **/
@Component
@Data
public class Student implements Serializable {
    @Value("1")
    private Long id;
    @Value("李四")
    private String name;
    @Value("18")
    private String age;
}

3 配置檔案

application.yaml

server:
  port: 8110 # 服務埠

spring:

  #spring:
  redis:
    host:  # 主機地址
    port: 7003 # 埠
    database: 0
    password: 317311 # 預設為空
    timeout: 3000ms #最大等待時間,超時則丟擲異常,否則請求一直等待
    lettuce:
      pool:
        max-active: 20  #最大連線數,負值表示沒有限制,預設8
        max-wait: -1    #最大阻塞等待時間,負值表示沒限制,預設-1
        max-idle: 8     #最大空閒連線,預設8
        min-idle: 0     #最小空閒連線,預設0

測試

@SpringBootTest
public class RedisTest {


    /**
     * 注入我們交給spring管理的物件
     * 
     */
    @Resource
    private Student student;
    /**
     * 注入redis
     */
    @Resource
    private RedisTemplate<String, Student> redisTemplate;
    @Test
    void save(){
        // key 一般使用這個格式 look:student:id 用冒號隔開
        redisTemplate.opsForValue().set("look:student:id",new Student(),1, TimeUnit.MINUTES);
    }

}

結果

發現RedisTemplate預設使用了JDK的序列化方式儲存了key和value

解決亂碼

建立RedisConfig配置檔案

@Configuration
public class RedisConfig {


    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        //首先解決key的序列化方式
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);

        //解決value的序列化方式
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);

        //序列化時將類的資料型別存入json,以便反序列化的時候轉換成正確的型別
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);

        // 解決jackson2無法反序列化LocalDateTime的問題
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.registerModule(new JavaTimeModule());

        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        return redisTemplate;
    }
}

效果如下