Springboot Session Redis存储与序列化及缓存注解

版本:
springboot 2.2.0
redis 4.0

Maven

<dependency>
    <groupId>org.springframework.sessiongroupId>
    <artifactId>spring-session-data-redisartifactId>
dependency>
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-data-redisartifactId>
dependency>

application.yml

spring:
  cache: # 用于支持缓存注册
    type: redis
    cache-names: c1,c2,c3 # 可配置多个Key前缀
    redis:
      time-to-live: 10m
  session: # 用户session存储
    store-type: redis
    timeout: 5m # session过期时间
    redis:
      namespace: session:redis # 存储在redis中的键名
  redis:
    host: 192.168.1.100
    port: 6379
    database: 0

Redis Session序列化配置

/**
 * SpringSession Redis序列化
 * *注:bean的名称必须为springSessionDefaultRedisSerializer
 *
 * @see org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration
 */
@Component("springSessionDefaultRedisSerializer")
public class SessionSerializer extends GenericJackson2JsonRedisSerializer {

}

RedisTemplate

适用于复杂对象的保存

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

    // 设置序列化工具 jackson2
    Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    jackson2JsonRedisSerializer.setObjectMapper(om);

    // 序列化设置
    // 默认
    // template.setDefaultSerializer(jackson2JsonRedisSerializer);
    // key-value
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(jackson2JsonRedisSerializer);
    // hash
    template.setHashKeySerializer(new StringRedisSerializer());
    template.setHashValueSerializer(jackson2JsonRedisSerializer);

    template.afterPropertiesSet();
    return template;
}

适用于简单键值对的保存

@Bean(name = "stringRedisTemplate")
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
    StringRedisTemplate template = new StringRedisTemplate();
    template.setConnectionFactory(redisConnectionFactory);
    return template;
}

示例

@Resource
private RedisTemplate redisTemplate;
@Resource
private StringRedisTemplate stringRedisTemplate;

stringRedisTemplate.opsForValue().set("spring:uid", "10001");
stringRedisTemplate.opsForValue().set("spring:name", "xxx");

Product product1 = new Product();
product1.setId(1001l);
product1.setName("apple");
product1.setCurMoney(new BigDecimal("19.9"));
product1.setDisabled(false);
product1.setCreateTime(new Date());
Product product2 = new Product();
product2.setId(1002l);
product2.setName("pair");
product2.setCurMoney(new BigDecimal("99.9"));
product2.setDisabled(true);
product2.setCreateTime(new Date());
redisTemplate.opsForHash().put("spring:hash", "product1", product1);
redisTemplate.opsForHash().put("spring:hash", "product2", product2);

redisTemplate.opsForSet().add("spring:set", product1, product2);

缓存注解

@Bean
public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) {
    // 初始化RedisCacheWriter
    RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());

    // ·设置默认的key前缀
    // ·设置序列化方式
    // ·设置过期时间,如果不设置,会使用spring.redis.time-to-live
    CacheKeyPrefix cacheKeyPrefix = name -> name + ":";
    RedisCacheConfiguration defaultRedisCacheConfiguration = RedisCacheConfiguration
            .defaultCacheConfig()
            .computePrefixWith(cacheKeyPrefix)
            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getKeySerializer()))
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()))
            .entryTtl(Duration.ofHours(1));
    RedisCacheConfiguration redisCacheConfiguration1 = RedisCacheConfiguration
            .defaultCacheConfig()
            .computePrefixWith(cacheKeyPrefix)
            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getKeySerializer()))
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()))
            .entryTtl(Duration.ofSeconds(100));
    RedisCacheConfiguration redisCacheConfiguration2 = RedisCacheConfiguration
            .defaultCacheConfig()
            .computePrefixWith(cacheKeyPrefix)
            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getKeySerializer()))
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()))
            .entryTtl(Duration.ofMinutes(5));

    // 根据cacheName设置不同的序列化方式和过期时间
    Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
    redisCacheConfigurationMap.put("c1", redisCacheConfiguration1);
    redisCacheConfigurationMap.put("c2", redisCacheConfiguration2);

    // 初始化RedisCacheManager
    RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, defaultRedisCacheConfiguration, redisCacheConfigurationMap);
    return cacheManager;
}

示例(方便演示,直接创建对象返回,可以从是否打印方法里的findById**来看有没有被缓存)

@Service
public class ProductService {

    @Cacheable(cacheNames = "c1", key = "'product'+#id")
    public Product findById(Long id) {
        System.out.println("findById" + id);
        Product product = new Product();
        product.setId(1001l);
        product.setName("apple");
        product.setCurMoney(new BigDecimal("19.9"));
        product.setDisabled(false);
        product.setCreateTime(new Date());
        return product;
    }

    @Cacheable(cacheNames = "c2", key = "'product'+#id")
    public Product findById2(Long id) {
        System.out.println("findById" + id);
        Product product = new Product();
        product.setId(1001l);
        product.setName("apple");
        product.setCurMoney(new BigDecimal("19.9"));
        product.setDisabled(false);
        product.setCreateTime(new Date());
        return product;
    }

    @Cacheable(cacheNames = "c3", key = "'product'+#id")
    public Product findById3(Long id) {
        System.out.println("findById" + id);
        Product product = new Product();
        product.setId(1001l);
        product.setName("apple");
        product.setCurMoney(new BigDecimal("19.9"));
        product.setDisabled(false);
        product.setCreateTime(new Date());
        return product;
    }

    @CacheEvict(value = "c3", key = "'product'+#id")
    public void deleteById(Long id) {
        System.out.println("deleteById" + id);
    }
}

你可能感兴趣的:(#,SpringBoot,#,Redis)