1、配置文件spring.redis.cluster.nodes=10.192.19.161:7001,10.192.19.161:7002,10.192.19.161:7003,10.192.19.162:7001,10.192.19.162:7002,10.192.19.162:7003
2、配置RedisCacheConfig
package com.mx.operationcenter.webframework.web.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
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.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;
import java.time.Duration;
import java.util.HashSet;
import java.util.Set;
/**
* 工程包名: com.mx.operationcenter.webframework.web.config
* 项目名称: futian
* 创建描述: heliangming 补充
* Creator: heliangming
* Create_Date: 20:37 2019-10-16
* Updater: heliangming
* Update_Date:20:37 2019-10-16
* 更新描述: heliangming 补充
**/
@Configuration
@EnableCaching
public class RedisCacheConfig {
@Value("${spring.redis.cluster.nodes:}")
private String clusterNodes;
@Bean
public RedisClusterConfiguration getRedisCluster() {
RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
Set<RedisNode> jedisClusterNodes = new HashSet<>();
String[] add = clusterNodes.split(",");
for (String temp : add) {
String[] hostAndPort = StringUtils.split(temp, ":");
jedisClusterNodes.add(new RedisNode(hostAndPort[0], Integer.parseInt(hostAndPort[1])));
}
redisClusterConfiguration.setClusterNodes(jedisClusterNodes);
//redisClusterConfiguration.setPassword(null);
return redisClusterConfiguration;
}
@Bean
public JedisPoolConfig getJedisPoolConfig() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(8);
jedisPoolConfig.setMaxIdle(8);
jedisPoolConfig.setMaxWaitMillis(3000);
return jedisPoolConfig;
}
@Bean
public JedisConnectionFactory redisConnectionFactory(RedisClusterConfiguration redisClusterConfiguration, JedisPoolConfig jedisPoolConfig) {
return new JedisConnectionFactory(redisClusterConfiguration, jedisPoolConfig);
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
redisTemplate.setConnectionFactory(cf);
//序列化配置
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);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
//定制缓存管理器的属性,自行做一些扩展和定制
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
//设置缓存过期时间1天
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(1));
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}
}
3、注解使用
package com.mx.operationcenter.webframework.cache.service.impl;
import com.mx.operationcenter.webframework.cache.service.AnnotationCacheService;
import com.mx.operationcenter.webframework.environment.dao.entity.TestCache;
import com.mx.operationcenter.webframework.environment.dao.TestCacheMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* 工程包名: com.mx.operationcenter.webframework.environment.service.impl
* 项目名称: futian
* 创建描述: heliangming 补充
* Creator: heliangming
* Create_Date: 16:29 2019-10-16
* Updater: heliangming
* Update_Date:16:29 2019-10-16
* 更新描述: heliangming 补充
**/
@Service
@CacheConfig(cacheNames = "AnnotationCacheService")
@Slf4j
public class AnnotationCacheServiceImpl implements AnnotationCacheService {
@Autowired
TestCacheMapper testCacheMapper;
//需要清除缓存元素的value值,beforeInvocation调用该方法之前清除缓存中的指定元素,方法出现异常,缓存也清除了--清除缓存
//allEntries为true时,Spring Cache将忽略指定的key。有的时候我们需要Cache一下清除所有的元素
//@CachesEvict 调用有此注解的方法可以删除多个缓存,很多时候一个操作会涉及到多个缓存的更新或删除--清除缓存
@CacheEvict(value="AnnotationCacheService",allEntries=true,beforeInvocation=true)
public int save(Map<String,String> map){
return testCacheMapper.save(map);
}
//如果存在就不再执行该方法,而是直接从缓存中获取结果进行返回,否则执行并将返回结果存入指定的缓存中--添加缓存
//若不指定key,默认策略生成key
@Cacheable(key = "'find'+#map")
public List<TestCache> find(Map<String,String> map){
return testCacheMapper.find(map);
}
//需要清除缓存元素的value值,beforeInvocation调用该方法之前清除缓存中的指定元素,方法出现异常,缓存也清除了--清除缓存
//@CachesEvict 调用有此注解的方法可以删除多个缓存,很多时候一个操作会涉及到多个缓存的更新或删除--清除缓存
@CacheEvict(allEntries=true,beforeInvocation=true)
public int delete(Map<String,String> map){
return testCacheMapper.delete(map);
}
//@CachePut(value="AnnotationCacheService",key = "'AnnotationCacheController:find'+map")//每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中--缓存更新
@CacheEvict(allEntries=true,beforeInvocation=true)
public int update(Map<String,String> map){
return testCacheMapper.update(map);
}
@CacheEvict(value="value",allEntries=true,beforeInvocation=true)
public void clear(String value){
log.info("--value-->"+value);
}
}
4、客户端使用
package com.mx.operationcenter.webframework.cache.service.impl;
import com.mx.operationcenter.webframework.cache.service.RedisService;
import com.mx.operationcenter.webframework.core.tools.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
/**
* 工程包名: com.mx.operationcenter.webframework.cache.service.impl
* 项目名称: futian
* 创建描述: heliangming 补充
* Creator: heliangming
* Create_Date: 9:23 2019-10-21
* Updater: heliangming
* Update_Date:9:23 2019-10-21
* 更新描述: heliangming 补充
**/
@Service
public class RedisServiceImpl implements RedisService {
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 一周有多少秒
*/
private static final long WEEK_SECONDS = 1 * 24 * 60 * 60;
/**
* 将 key,value 存放到redis数据库中,默认设置过期时间为一天
* @param key
* @param value
*/
public void set(String key, Object value) {
redisTemplate.opsForValue().set(key, JsonUtil.convertObj2String(value), WEEK_SECONDS, TimeUnit.SECONDS);
}
/**
* 将 key,value 存放到redis数据库中,设置过期时间单位是秒
*
* @param key
* @param value
* @param expireTime
*/
public void set(String key, Object value, long expireTime) {
redisTemplate.opsForValue().set(key, JsonUtil.convertObj2String(value), expireTime, TimeUnit.SECONDS);
}
/**
* 判断 key 是否在 redis 数据库中
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 获取与 key 对应的对象
* @param key
* @param clazz 目标对象类型
* @param <T>
* @return
*/
public <T> T get(String key, Class<T> clazz) {
String s = get(key);
if (s == null) {
return null;
}
return JsonUtil.convertString2Obj(s, clazz);
}
/**
* 获取 key 对应的字符串
* @param key
* @return
*/
public String get(String key) {
return redisTemplate.opsForValue().get(key);
}
/**
* 删除 key 对应的 value
* @param key
*/
public void delete(String key) {
redisTemplate.delete(key);
}
}