1.增加pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
2.配置redis连接
# redis配置
spring:
redis:
database: 0
host: 10.0.0.36
password: 123456
port: 6379
timeout: 5000
lettuce:
pool:
max-active: 300
max-wait: -1
max-idle: 20
min-idle: 10
3.启动类添加 @EnableCaching // 开启缓存
4. keyGenerator
:key 的生成器。 key 和 keyGenerator 二选一使用
@Configuration
public class MyCacheConfig {
@Bean("myKeyGenerator")
public KeyGenerator keyGenerator(){
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
return method.getName()+"["+ Arrays.asList(params).toString() +"]";
}
};
}
}
5.service实现
@Cacheable(cacheNames = "eo",key = "#id")
public Integer getEo(int id) throws Exception{
log.info("111");
Thread.sleep(1000);
log.info("id is {}",id);
return id;
}
@Cacheable(cacheNames = "eo1",keyGenerator = "myKeyGenerator")
public Integer getEo1(int id) throws Exception{
log.info("222");
Thread.sleep(1000);
log.info("id is {}",id);
return id;
}
6.controller
@GetMapping("/xx")
public Integer xx(Integer id) throws Exception {
return cacheService.getEo(id);
}
@GetMapping("/xx1")
public Integer xx1(Integer id) throws Exception {
return cacheService.getEo1(id);
}
7.RedisConfig
/**
* 自定义缓存管理器
*/
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
Set<String> cacheNames = new HashSet<>();
cacheNames.add("eo");
cacheNames.add("eo1");
ConcurrentHashMap<String, RedisCacheConfiguration> configMap = new ConcurrentHashMap<>();
configMap.put("eo", config.entryTtl(Duration.ofMinutes(1L)));
configMap.put("eo1", config);
//需要先初始化缓存名称,再初始化其它的配置。
RedisCacheManager cacheManager = RedisCacheManager.builder(factory).initialCacheNames(cacheNames).withInitialCacheConfigurations(configMap).build();
return cacheManager;
}
8.运行结果
2022-05-13 15:10:49.818 INFO 344756 --- [nio-8080-exec-2] com.example.demo.cache.CacheService : 111
2022-05-13 15:10:50.818 INFO 344756 --- [nio-8080-exec-2] com.example.demo.cache.CacheService : id is 3
2022-05-13 15:12:03.241 INFO 344756 --- [nio-8080-exec-9] com.example.demo.cache.CacheService : 111
2022-05-13 15:12:04.242 INFO 344756 --- [nio-8080-exec-9] com.example.demo.cache.CacheService : id is 3
2022-05-13 15:17:33.073 INFO 344756 --- [nio-8080-exec-4] com.example.demo.cache.CacheService : 111
2022-05-13 15:17:34.073 INFO 344756 --- [nio-8080-exec-4] com.example.demo.cache.CacheService : id is 3
2022-05-13 15:18:01.530 INFO 344756 --- [nio-8080-exec-8] com.example.demo.cache.CacheService : 222
2022-05-13 15:18:02.531 INFO 344756 --- [nio-8080-exec-8] com.example.demo.cache.CacheService : id is 1