1.增加maven依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.增加redis配置(application.yaml)
spring:
redis:
database: 0
host: localhost
3.增加CacheManager配置
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.cache.RedisCacheWriter; import org.springframework.data.redis.core.RedisTemplate; import java.time.Duration; import java.util.HashMap; import java.util.Map; @EnableCaching @Configuration public class CacheConfiguration { @Autowired private RedisTemplate redisTemplate; @Bean public RedisCacheWriter writer() { return RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory()); } @Bean public CacheManager cacheManager() { Map<String, RedisCacheConfiguration> configurationMap = new HashMap<>(); configurationMap.put("cache1", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(1))); configurationMap.put("cache2", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(2))); return RedisCacheManager.builder(writer()) .initialCacheNames(configurationMap.keySet()) .withInitialCacheConfigurations(configurationMap) .build(); } }