您的位置:首页 > 数据库 > Redis

springboot使用redis缓存

lizhiqiang1217 2019-05-24 20:47 585 查看 https://blog.csdn.net/lizhiqia

1、pom引入依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>

2、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<String, String> 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);
}
}

3、注解使用

@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,使用@Cacheable的时候报错:java.lang.ClassCastException
解决办法:是因为热部署的依赖导致的。注释掉就好了。

标签: