Redisson提供了将Redis无缝整合到Spring框架的能力。Redisson依照Spring Cache标准提供了基于Redis的Spring缓存实现。 每个缓存(Cache)实例都提供了了两个重要的可配置参数:过期时间(ttl)
和最长空闲时间(maxIdleTime)
,如果这两个参数都未指定或值为0
,那么实例管理的数据将永久保存。
Jar包
<!-- JDK 1.8+ compatible -->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.7.5</version>
</dependency>
RedissonCacheConfig 缓存配置类
创建一个RedissonClient客户端对象,生成了CacheManager缓存管理器,配置一个名叫“testMap”的缓存器,最大缓存时间为24分钟,最大空闲时间12分钟(客户端连接过期时间)
@Configuration
@EnableCaching
public class RedissonCacheConfig {
@Bean(destroyMethod="shutdown")
RedissonClient redisson() throws IOException {
Config config = new Config();
//config.setCodec(new JsonJacksonCodec()); 默认
config.useClusterServers()
.addNodeAddress("redis://192.168.56.128:7000", "redis://192.168.56.128:7001","redis://192.168.56.128:7002");
return Redisson.create(config);
}
@Bean
CacheManager cacheManager(RedissonClient redissonClient){
Map<String,CacheConfig> config = new HashMap<>(16);
// create "testMap" cache with ttl = 24 minutes and maxIdleTime = 12 minutes
config.put("testMap",new CacheConfig(24*60*1000,12*60*1000));
return new RedissonSpringCacheManager(redissonClient,config);
}
}
UserServiceImpl 服务类
@Cacheable 属性value指定缓存,属性key指定缓存对象的标识
@Service("userService")
public class UserServiceImpl implements UserService {
private UserMapper userMapper;
@Cacheable(value="testMap",key="targetClass.getName()+'.'+methodName+'.'+#id")
@Override
public User searchUserById(int id) throws Exception {
return userMapper.findUserById(id);
}
}
当我们去执行userService的searchUserById服务方法时,第一次执行去数据库(mysql)中查询数据(耗时较大),完成后将结果缓存到redis中,再次查询时直接从redis缓存中取出并返回(耗时较小)
连接redis 观察存储对象值
存储结构为hash,key值为@Cacheable的key属性,value值为对象的json形式
参考