SpringBoot集成Redisson替换SpringCache底层容器实现

Redisson的引入和配置方式,见:上一篇文章

配置

在RedissonConfig.java中添加以下代码

/**
* redis作为springcache的缓存底层实现
* springcache看作是一个约定好的上层接口,redis就是底层实现
*
* @param redissonClient
* @return
*/
@Bean
public CacheManager cacheManager(RedissonClient redissonClient) {
List<RedissonProperties.CacheGroup> cacheGroup = redissonProperties.getCacheGroup();
Map<String, CacheConfig> config = new HashMap<>();
for (RedissonProperties.CacheGroup group : cacheGroup) {
CacheConfig cacheConfig = new CacheConfig(group.getTtl() * 1000 * 60, group.getMaxIdleTime() * 1000 * 60);
cacheConfig.setMaxSize(group.getMaxSize());
config.put(group.getGroupId(), cacheConfig);
}
return new RedissonSpringCacheManager(redissonClient, config, new JsonJacksonCodec(objectMapper));
}

// 将自定义将生成器加载进spring容器
@Bean("MyKeyGenerator")
public KeyGenerator getKeyGenerator() {
return new MyKeyGenerator();
}

// TODO 其中MyKeyGenerator为在RedissonConfig.java中的内部类
// MyKeyGenerator.java
@Component
class MyKeyGenerator implements KeyGenerator {

/**
* 自定义键生成策略(防止相同入参下缓存键冲突)
*
* @param target
* @param method
* @param params
* @return
*/
@Override
public Object generate(Object target, Method method, Object... params) {
return target.getClass().getName() + method.getName() +
Stream.of(params).map(Object::toString).collect(Collectors.joining(","));
}
}

使用方式

在需要引入SpringCache的方法上添加以下注解

@Cacheable(cacheNames = "springCacheTest", keyGenerator = "MyKeyGenerator")
@GetMapping("/toCache")
public String toCache() {
return cacheService.toTestSpringCache();
}

@Cacheable(cacheNames = "springCacheTest", keyGenerator = "MyKeyGenerator")
@GetMapping("/toCacheObj")
public Map<Object, Object> toCacheOjb() {
return cacheService.toTestSpringCacheObj();
}