pom.xml
导入依赖
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-cache -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
启动类加入启用缓存注解
@EnableCaching
application.yml指定缓存类型(例如redis),缓存存活时间(单位:毫秒)
spring:
cache:
type: redis
redis:
time-to-live: 3600000
// 给方法上加入注解
// 注意key的值是SpEL表达式,故要加单引号
// value为缓存名字
// key表达式可见 https://docs.spring.io/spring/docs/5.2.6.RELEASE/spring-framework-reference/integration.html#cache-spel-context
@Cacheable(value = {"product"}, key="'customkey'")
// 自定义缓存配置
package dev.painaodai.cloud.member.config;
import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class CustomCacheConfig {
@Bean
RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
redisCacheConfiguration = redisCacheConfiguration.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.string()));
redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json()));
// redisCacheConfiguration = redisCacheConfiguration.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
// redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));
CacheProperties.Redis redisProperties = cacheProperties.getRedis();
// 过期时间
if(redisProperties.getTimeToLive() != null){
redisCacheConfiguration = redisCacheConfiguration.entryTtl(redisProperties.getTimeToLive());
}
// 自定义前缀
if(redisProperties.getKeyPrefix() != null){
redisCacheConfiguration = redisCacheConfiguration.prefixKeysWith(redisProperties.getKeyPrefix());
}
// 是否缓存空值
if(!redisProperties.isCacheNullValues()){
redisCacheConfiguration = redisCacheConfiguration.disableCachingNullValues();
}
// 是否启用前缀
if(!redisProperties.isUseKeyPrefix()){
redisCacheConfiguration = redisCacheConfiguration.disableKeyPrefix();
}
return redisCacheConfiguration;
}
}