spring:
redis:
##默认redis客户端连接为0 可修改
database: 0
host: 127.0.0.1
port: 6379
cache_name: XiChuanRedis
##password:
pool:
##连接池最大空闲连接
max-idle: 8
min-idle: 0
max-active: 8
max-wait: 1
timeout: 5000
package org.springblade.common.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
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.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@Configuration
public class RedisConfig {
private Duration timeToLive = Duration.ofHours(1);
@Bean
public RedisTemplate<Object, Object> edisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 使用Jackson2JsonRedisSerialize 替换默认序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
// 设置value的序列化规则和 key的序列化规则
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer 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 config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(timeToLive)
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}
@Component public classBaseServiceImpl{ @Autowired ParamRepository paramRepository; @Cacheable(value="XiChuanRedis", key="'sign_test'") public String getNotFinishedTypeCode(){ List<Param> params = paramRepository.findBySpiderOver(0); if(params != null && params.size() > 0){ return params.stream() //先将List按照id进行排序,然后取出最上面的那个,然后取出第一个 .sorted(Comparator.comparing(HeiGuangParam::getId)) .collect(Collectors.toList()) .get(0) .getTypeCode(); }else{ //如果没有就返回null return null; } } /** * 更新param后,需要将redis中的值移除 * @param param */ @CacheEvict(value="XiChuanRedis", key="'sign_test'") public void updateParamByTypeCode(Param param){ paramRepository.save(param); } }
@Cacheable:如果redis在相同的Cache有相同的key的缓存元素时,就会直接在redis缓存中,根据key读取缓存并返回结果;如果没有,则先调用方法,将返回值写入到redis缓存中,然后返回结果。它的属性有:value、key、condition
value:指定是哪一个Cache,可以指定多个Cache。例如:@Cacheable({"cache1", "cache2"})
key:缓存的key,当在清楚缓存时要与此对应。
1.key为null,则使用默认key。
2.key为一个字符串,例如:@CacheEvict(value="XiChuanRedis", key="'department_code_'")。
3.key为方法中的一个方法上的一个属性,例如:
@CacheEvict(value="XiChuanRedis", key="'code_'+#departmentCode") public String getNameByCode(String departmentCode){ }
4.key为方法中的一个方法上的一个实体的属性,例如:
@Cacheable(value="XiChuanRedis", key="'userid_'+#user.id") public User getUserById(Integer id){ }
condition:缓存条件,可以直接为null,例子如下:
@Cacheable(value="XiChuanRedis", key="'userid_'+#user.id", condition="#user.id%2==0") public User getUserById(Integer id){ }