SpringBoot系列二十四:整合Redis

1、pom引入依赖


    org.springframework.boot
    spring-boot-starter-data-redis

2、yml配置

spring:
  redis:
    database: 10
    host: 10.18.28.115
    port: 6379
    password: root
    timeout: 43200000

3、redis配置

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    /**
    * 自定义redis key值生成策略
    */
    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            for (Object obj : params) {
                sb.append(obj.toString());
            }
            return sb.toString();
        };
    }
    
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
      ObjectMapper om = new ObjectMapper();
      om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
      om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
      //redis序列化
      Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
      jackson2JsonRedisSerializer.setObjectMapper(om);

      StringRedisTemplate template = new StringRedisTemplate(factory);
      template.setValueSerializer(jackson2JsonRedisSerializer);
      template.afterPropertiesSet();
      return template;
    }

    /**
    * 自定义CacheManager
    */
    @Bean
     public CacheManager cacheManager(RedisTemplate redisTemplate) {
         //全局redis缓存过期时间
         RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(1));  
         RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
        return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
    }
}

4、注解使用

@Cacheable
@Cacheable("product")
@Cacheable(value = {"product","order"}, key = "#root.targetClass+'-'+#id")
@Cacheable(value = "product", key = "#root.targetClass+'-'+#id")
自定义cacheManager
@Cacheable(value = "product", key = "#root.targetClass+'-'+#id” cacheManager="cacheManager")

// 应用到写数据的方法上,如新增/修改方法
@CachePut
@CachePut(value = "product", key = "#root.targetClass+'-'+#product.id")

// 即应用到移除数据的方法上,如删除方法
@CacheEvict 
@CacheEvict(value = "product", key = "#root.targetClass+'-'+#id")

Spring Cache提供了一些供我们使用的SpEL上下文数据,下表直接摘自Spring官方文档:
SpringBoot系列二十四:整合Redis_第1张图片

注意:
 在springboot集成redis,使用@Cacheable的时候报错:java.lang.ClassCastException
解决办法:是因为热部署的依赖导致的。注释掉就好了。
SpringBoot系列二十四:整合Redis_第2张图片
5、使用redisTemplate
Redis常见的五大数据类型:
 String(字符串)、List(列表)、Set(集合)、Hash(散列)、ZSet(有序集合)
 stringRedisTemplate.opsForValue():操作String(字符串)
 stringRedisTemplate.opsForList():操作List(列表)
 stringRedisTemplate.opsForSet():操作Set(集合)
 stringRedisTemplate.opsForHash():操作Hash(散列)
 stringRedisTemplate.opsForZSet():操作ZSet(有序集合)

@Autowired
StringRedisTemplate stringRedisTemplate;//操作k-v都是字符串的
@Autowired
RedisTemplate redisTemplate;//k-v都是对象的
    
 @Test
    public void test01(){
        //默认如果保存对象,使用jdk序列化机制,序列化后的数据保存到redis中
        redisTemplate.opsForValue().set("emp-01",empById);
        stringRedisTemplate.opsForValue().append("msg","hello");
        String msg = stringRedisTemplate.opsForValue().get("msg");
        System.out.println(msg);

        stringRedisTemplate.opsForList().leftPush("mylist","1");
        stringRedisTemplate.opsForList().leftPush("mylist","2");
    }

你可能感兴趣的:(SpringBoot)