写的很简单,为了实现功能。如果有错误,请大佬指出。
1.添加依赖2.配置redis信息org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-starter-cache
spring: redis: host: localhost #地址 post: 6379 #端口 password: xxxx #密码,没有可以不用写 database: 0 #使用redis中的哪个库 timeout: 3000 #超时时间,单位是毫秒3.在启动类添加@EnableCaching注解
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4.在方法上添加@Cacheable注解,value代表存储时的key值。
@Override
@Cacheable(value = "XX")
public List XX(Integer Id) {
...
}
5.配置一个配置类CacheConfig
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheWriter redisCacheWriter = RedisCacheWriter.lockingRedisCacheWriter(connectionFactory);
RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
cacheConfiguration = cacheConfiguration.entryTtl(Duration.ofSeconds(60));
RedisCacheManager redisCacheManager = new RedisCacheManager(redisCacheWriter,cacheConfiguration);
return redisCacheManager;
}
}
以上配置完就可以实现缓存功能。
注:如果碰到异常:Cannot serialize,说明实体类没有被序列化,将实体类继承Serializable。



