pom.xml依赖:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.6.RELEASE</version>
</dependency>
<dependency>
<groupId>biz.paluch.redis</groupId>
<artifactId>lettuce</artifactId>
<version>4.4.0.Final</version>
</dependency>
代码:
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
/**
* 自定义缓存机制
* @author ray.sun
*
*/
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory cf) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
redisTemplate.setConnectionFactory(cf);
return redisTemplate;
}
@Bean
public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
//设置默认过期时间,单位秒,此处设置为1天
cacheManager.setDefaultExpiration(3600 * 24);
return cacheManager;
}
}
#############################################
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.stereotype.Service;
/**
*
* @author ray.sun
*
*/
@Service
public class RedisCacheFlusher implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
private RedisConnectionFactory connFactory;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
Set<byte[]> keys = connFactory.getConnection().keys(RedisCacheKeyGenerator.PREFIX_PATTERN.getBytes());
keys.forEach(e -> {
connFactory.getConnection().del(e);
});
}
}
#######################################
import java.lang.reflect.Method;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
import org.springframework.stereotype.Service;
/**
* 该类用来生成缓存的key, 重写方法generate, 定义适合业务需要的key
* @author ray.sun
*
*/
@Service
public class RedisCacheKeyGenerator implements KeyGenerator {
private static final String PREFIX = "AppName_";
public static final String PREFIX_PATTERN = "*AppName*";
public static final String EMPTY = "";
@SuppressWarnings("rawtypes")
@Override
public Object generate(Object target, Method method, Object... params) {
// get class name
Class[] interfaces = target.getClass().getInterfaces();
String className;
if (interfaces == null || interfaces.length == 0) {
className = target.getClass().getSimpleName();
} else {
className = interfaces[0].getSimpleName();
}
// get parameter value
String paramValue;
if (params.length == 0) {
paramValue = EMPTY;
} else {
paramValue = SimpleKeyGenerator.generateKey(params).toString();
}
StringBuilder sb = new StringBuilder(PREFIX);
sb.append(className).append(method.getName()).append(paramValue);
return sb.toString();
}
}
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.session.data.redis.config.ConfigureRedisAction;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
/**
* 该类用于定义redis server端参数
* @author ray.sun
*
*/
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600)
public class RedisConfig {
@Value("${redis.masterName}")
private String masterName;
@Value("${redis.sentinels}")
private String[] sentinels;
@Value("${redis.databaseIndex}")
private int redisDb;
@Bean
public RedisConnectionFactory connectionFactory() {
Set<String> sentinelHostAndPorts = new HashSet<String>();
for (String sentinel : sentinels) {
sentinelHostAndPorts.add(sentinel);
}
RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration(masterName, sentinelHostAndPorts);
LettuceConnectionFactory redisFactory = new LettuceConnectionFactory(sentinelConfig);
redisFactory.setDatabase(redisDb);
return redisFactory;
}
@Bean
public static ConfigureRedisAction configureRedisAction() {
return ConfigureRedisAction.NO_OP;
}
}
//给服务层添加缓存
@Cacheable(value = "自定义缓存名字",
keyGenerator = "redisCacheKeyGenerator", //该值与前面定义的service 类RedisCacheKeyGenerator的名字一致,只是首字母小写了
unless="#result.attr1 == null") //定义不需要缓存的情况,unless可选
public Province getProvince(String provinceName, Date date){
...
}
//也可以给持久层添加缓存,方法相同
...