在分布式服务中,使用基于内存和硬盘的缓存显然已经不现实了,更为常用的做法是使用基于redis的缓存
使用redis缓存首先准备redis,这个不难,不再赘述。
引入redis的依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency>
spring:
redis:
#数据库索引
database: 2
host: 127.0.0.1
port: 6379
password: abc
jedis:
pool:
max-active: 8
max-wait: -1ms
max-idle: 8
min-idle: 0
timeout: 300s
@Configuration public class RedisConfig extends CachingConfigurerSupport { @Bean public RedisCacheManager cacheManager(RedisConnectionFactory factory) { return RedisCacheManager.create(factory); } @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, String> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(factory); return redisTemplate; } }
具体的使用还是下面这三个注解,想要了解更多可以查看上篇博文springboot使用缓存(二)
@Cacheable
@CacheEvict
@CachePut
参考:
https://developer.51cto.com/art/202001/609199.htm
https://www.jianshu.com/p/8b026187dc62
原文:https://www.cnblogs.com/wangbin2188/p/15011862.html