Spring Cache可以通过配置多级缓存来达到一级缓存查询Caffeine,Caffeine查询不到查询Redis缓存,Redis查询不到查询数据库的效果。需要在Spring配置文件中配置多个CacheManager,并将其分别配置为不同的缓存源,例如Caffeine和Redis,然后使用组合模式将它们结合起来。
1.首先,需要在pom.xml文件中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.Caffeine和Redis的CacheManager
@Configuration
@EnableCaching
public class CacheConfig {
@Value("${cache.caffeine.maximumSize}")
private int maximumSize;
@Value("${cache.caffeine.expireAfterWriteSeconds}")
private int expireAfterWriteSeconds;
@Value("${cache.redis.time-to-live-seconds}")
private long redisTimeToLiveSeconds;
@Bean
public CaffeineCacheManager caffeineCacheManager() {
CaffeineCacheManager cacheManager = new CaffeineCacheManager();
cacheManager.setCaffeine(caffeineCacheBuilder());
return cacheManager;
}
@Bean
public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(redisTimeToLiveSeconds));
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(redisCacheConfiguration)
.build();
}
private Caffeine<Object, Object> caffeineCacheBuilder() {
return Caffeine.newBuilder()
.expireAfterWrite(expireAfterWriteSeconds, TimeUnit.SECONDS)
.maximumSize(maximumSize);
}
}
3.将Caffeine和Redis的CacheManager结合起来
@Configuration
public class CacheConfig {
...
@Bean
public CompositeCacheManager compositeCacheManager(CaffeineCacheManager caffeineCacheManager,
RedisCacheManager redisCacheManager) {
CompositeCacheManager compositeCacheManager = new CompositeCacheManager();
compositeCacheManager.setCacheManagers(Arrays.asList(caffeineCacheManager, redisCacheManager));
compositeCacheManager.setFallbackToNoOpCache(false); // 关闭缓存未命中时自动创建的空缓存
return compositeCacheManager;
}
...
}
如上 Arrays.asList(caffeineCacheManager, redisCacheManager) 中caffeineCacheManager放在前面,即先查询caffeineCacheManager缓存,未命中则查询redisCacheManager。顺序很重要,别搞错!
4.使用多级缓存
在需要缓存的方法上添加@Cacheable注解,并指定缓存名称
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
@Cacheable(value = {"userCache"})
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
...
}
5.在application.properties文件中配置缓存参数
cache.caffeine.maximumSize=1000
cache.caffeine.expireAfterWriteSeconds=300
cache.redis.time-to-live-seconds=600
通过如上5个步骤即可实现多级缓存。
在Redis单独作为缓存性能都无法满足时,可以使用多级缓存。