导读
当项目数据量大的时候,每次从数据库中查询数据要话费很长时间,不但影响用户的体验度,而且浪费了数据库的资源,所以需要额外增加中间件Redis来考虑解决,当然添加其他中间件也可以,目前仅仅简单的介绍下SpringBoot项目中使用Redis。
使用
添加依赖
<dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-redis</artifactId><version>2.1.14.RELEASE</version></dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>3.0.1</version></dependency>
添加配置信息
redis:host: localhostport: 6379password: 123456database: 0timeout: 15000jedis:pool:min-idle: 4max-idle: 8max-active: 40max-wait: 15000numTestsPerEvictionRun: 3minEvictableIdleTimeMillis: 300000timeBetweenEvictionRunsMillis: 300000testOnBorrow: truetestOnReturn: truetestWhileIdle: true
RedisConfig文件
import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;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.connection.RedisConnectionFactory;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.RedisSerializationContext;import java.io.Serializable;import java.time.Duration;import java.util.HashMap;import java.util.Map;/*** RedisConfig配置文件*/@Configuration@EnableCachingpublic class RedisConfig implements Serializable {/*** KeyGenerator该方法设置key的生成策略*//**@Beanpublic KeyGenerator keyGenerator() {return new KeyGenerator() {//为给定的方法及其参数生成一个键//格式为:com.frog.mvcdemo.controller.FrogTestController-show-[params]@Overridepublic Object generate(Object target, Method method, Object... params) {StringBuffer sb = new StringBuffer();sb.append(target.getClass().getName());//类名sb.append("-");sb.append(method.getName());//方法名sb.append("-");for (Object param: params ) {sb.append(param.toString());//参数}return sb.toString();}};}*//*** 设置redis缓存过期时间*/@Beanpublic RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {return new RedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),// 默认策略,未配置的 key 会使用这个 这里设置一个月this.getRedisCacheConfigurationWithTtl(60 * 60 * 12 * 30),this.getRedisCacheConfigurationMap() // 指定 key 策略);}private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();//自定义设置缓存时间 这里设置12hredisCacheConfigurationMap.put("defineCache", this.getRedisCacheConfigurationWithTtl(60 * 60 * 12));return redisCacheConfigurationMap;}private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(om);RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)).entryTtl(Duration.ofSeconds(seconds));return redisCacheConfiguration;}}
在实现层使用
a.未使用配置文件中key生成策略
未使用默认的key生成策略,也就是上述配置文件失效,使用@Cacheable注解,具体该注解如何使用,可以参考该篇文章:Spring缓存注解@Cacheable,@CachePut , @CacheEvict使用
@Override@Cacheable(value = "defineCache", key = "#demoQuery.toGetKeyString()",unless = "#result==null||#result.size()<=0")public List<DemoVO> getAppRuleList(DemoQuery demoQuery) {return demoMapper.getDemoList(demoQuery);}
DemoQuery添加 toGetKeyString 方法
public String toGetKeyString() {return "toGetKeyString{" +"name='" + name + '\'' +", age='" + age + '\'' +", address='" + address + '\'' +", phone='" + phone + '\'' +", job=" + job +", birthday='" + birthday + '\'' +'}';}
b.使用配置文件中key生成策略
@Override@Cacheable(value = "defineCache", keyGenerator = "keyGenerator",unless = "#result==null||#result.size()<=0")public List<DemoVO> getAppRuleList(DemoQuery demoQuery) {return demoMapper.getDemoList(demoQuery);}
自定义策略: key属性是用来指定Spring缓存方法的返回结果时对应的key的。该属性支持SpringEL表达式。当我们没有指定该属性时,Spring将使用默认策略生成key。
自定义策略是指我们可以通过Spring的EL表达式来指定我们的key。这里的EL表达式可以使用方法参数及它们对应的属性。使用方法参数时我们可以直接使用“#参数名”或者“#p参数index”。
注意
- 使用@Cacheable注解的时候,指定的key不能是该类内部的方法,必须要从其他地方引用,不然会报错。
END
搞定~
