SpringBoot+Redis的基本使用

47677777發表於2024-03-19

SpringBoot+Redis的基本使用

[toc]

一、SpringBoot+Redis 快取資料

1、新增依賴

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

        <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>

2、新增配置:

spring:
  data:
    redis:
      host: localhost
      port: 6379
      password:
      database: 0
      lettuce:
        pool:
          max-active: 8 # 連線池最大連線數,預設 8
          min-idle: 0 # 連線池最小空閒連線數,預設 0
          max-wait: -1ms # 連線池最大等待時間(使用負值表示沒有限制),預設 -1
          max-idle-time: 1800000ms # 連線池中的最大空閒連線數,預設 8

3、配置redis的序列化,啟用快取:

@EnableCaching
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        ObjectMapper objectMapper = new ObjectMapper();
        //FAIL_ON_UNKNOWN_PROPERTIES在序列化的時候,如果遇到不認識的欄位的處理方式
        //預設啟用特性,這意味著在遇到未知屬性時丟擲JsonMappingException。在引入該特性之前,這是預設的預設設定。
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        //FAIL_ON_EMPTY_BEANS決定了在沒有找到型別的存取器時發生了什麼(並且沒有註釋表明它是被序列化的)。如果啟用(預設),
        // 將丟擲一個異常來指明這些是非序列化型別;如果禁用了,它們將被序列化為空物件,即沒有任何屬性。
        //請注意,這個特性只對那些沒有任何識別註釋的“空”bean產生影響(如@json序列化):那些有註釋的bean不會導致丟擲異常。
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);

        //在序列化時,只有那些值為null或被認為為空的值的屬性才不會被包含在內。
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

        //objectMapper.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);

        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
        //是否允許單引號
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(objectMapper,Object.class);

        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addSerializer(LocalDate.class,new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addSerializer(LocalTime.class,new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
        javaTimeModule.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addDeserializer(LocalDate.class,new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addDeserializer(LocalTime.class,new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
        objectMapper.registerModule(javaTimeModule);


        template.setValueSerializer(jackson2JsonRedisSerializer);
        // 使用StringRedisSerializer來序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {

        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ZERO);
        return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory))
                .cacheDefaults(redisCacheConfiguration).build();
    }


}

4、使用:
呼叫被快取註解修飾的方法時,會自動從快取中查資料。


@Transactional
@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    // insert、update用 @CachePut 註解
    @CachePut(value = "userCache",key = "#user.id")
    @Override
    public void updateById(User user) {
        userMapper.updateById(user);
    }

    // select 的時候使用 @Cacheable
    @Cacheable(value = "userCache",key="#uid")
    @Override
    public User findById(Integer uid) {
        return userMapper.findById(uid);
    }

    // 刪除的時候使用 @CacheEvict
    @CacheEvict(value = "userCache",key = "#uid")
    @Override
    public void delById(Integer uid) {
        userMapper.delById(uid);
    }


}