1.配置
application.yml
spring:
application:
name: meter-highway
profiles:
active: druid,mongodb,dubbo,rabbitmq,redis
application-redis.yml
spring:
redis:
database: 9
host: 192.168.13.146
port: 6379
password: Luban376
timeout: 2000
2.依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
3.config Bean
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
RedisSerializer<String> stringRedisSerializer = new StringRedisSerializer();
GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();
template.setKeySerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.setValueSerializer(valueSerializer);
template.setHashValueSerializer(valueSerializer);
return template;
}
private static String PREFIX = "METER::";
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.prefixKeysWith(PREFIX)
.entryTtl(Duration.ofSeconds(2*60))//过期超时时间 2分钟
.disableCachingNullValues();
return new MeterCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(factory),config);
}
}
public class MeterCacheManager extends RedisCacheManager {
public MeterCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
super(cacheWriter, defaultCacheConfiguration);
}
@Override
protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
if(!StringUtils.isEmpty(name) && name.contains("#")) {//#数字是秒
String numStr = name.split("#")[1];
if(StringUtils.isNumeric(numStr)) {
return super.createRedisCache(name, cacheConfig.entryTtl(Duration.ofSeconds(Integer.parseInt(numStr))));
}
}
return super.createRedisCache(name, cacheConfig);
}
}
标签:redis,return,name,Spring,Redis,整合,spring,public,template From: https://www.cnblogs.com/Acaak/p/17560036.html