SpringBoot通过Cacheable注解完成redis缓存功能
2021-04-16 04:28
标签:文件引入 Fix ota long public turn depend data- tor 一、pom文件引入所需jar 二、config配置 三、使用注解 四、打完收功~ SpringBoot通过Cacheable注解完成redis缓存功能 标签:文件引入 Fix ota long public turn depend data- tor 原文地址:https://www.cnblogs.com/timeflying/p/13323942.htmlimport org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.*;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.time.Duration;
import java.util.Map;
/**
* @Description: redis缓存配置: 重载redisCacheManager实现过期时间可配置
**/
@Configuration
@EnableTransactionManagement
@CacheConfig
@EnableCaching
public class RedisCacheConfig {
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
//初始化一个RedisCacheWriter
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
//初始化一个RedisCacheConfiguration
RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();
//返回一个自定义的CacheManager
return new CustomizeTtlRedisCacheManager(redisCacheWriter, defaultCacheConfig);
}
}
/**
* @Description: 重载redisCacheManager-从cacheName中提取过期时间进行配置
**/
class CustomizeTtlRedisCacheManager extends RedisCacheManager {
public CustomizeTtlRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
super(cacheWriter, defaultCacheConfiguration);
}
public CustomizeTtlRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration, String... initialCacheNames) {
super(cacheWriter, defaultCacheConfiguration, initialCacheNames);
}
public CustomizeTtlRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration, boolean allowInFlightCacheCreation, String... initialCacheNames) {
super(cacheWriter, defaultCacheConfiguration, allowInFlightCacheCreation, initialCacheNames);
}
public CustomizeTtlRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration, Map
/**cacheNames中的"#30"表示缓存过期时间为30秒 */
@Cacheable(cacheNames = "testMethod#30", unless = "#result==null")
public String testMethod(String param) {
// TODO
}
文章标题:SpringBoot通过Cacheable注解完成redis缓存功能
文章链接:http://soscw.com/index.php/essay/76050.html