集群模式:
配置文件设置:
###REDIS (RedisProperties) redis集群配置
########################################################
# Redis服务器地址
#spring.redis.host=127.0.0.1
# Redis服务器连接端口
#spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
spring.redis.commandTimeout=5000
# redis.cluster
spring.redis.cluster.nodes=172.16.88.102:7001,172.16.88.103:7003,172.16.88.104:7005,172.16.88.102:7002,172.16.88.103:7004,172.16.88.104:7006
#服务器上下文路径
spring.redis.contextPath=contextPath
java配置文件:
package com.mobile.mobilemap.manage.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.KeyGenerator;
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.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
//import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
//redis配置
@Configuration
@ConditionalOnClass({Jedis.class})
public class RedisConfig {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${spring.redis.cluster.nodes}")
private String clusterNodes;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.pool.max-wait}")
private long maxWaitMillis;
@Value("${spring.redis.commandTimeout}")
private int commandTimeout;
@Bean
public JedisCluster getJedisCluster() {
String[] cNodes = clusterNodes.split(",");
Set nodes = new HashSet<>();
// 分割出集群节点
for (String node : cNodes) {
String[] hp = node.split(":");
nodes.add(new HostAndPort(hp[0], Integer.parseInt(hp[1])));
}
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
// 创建集群对象
JedisCluster jedisCluster = new JedisCluster(nodes, commandTimeout);
return new JedisCluster(nodes, commandTimeout, jedisPoolConfig);
}
/**
* 注入 RedisConnectionFactory
*/
@Autowired
RedisConnectionFactory redisConnectionFactory;
/**
* 指定key的生成策略
*
* @return KeyGenerator
*/
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method,
Object... params) {
StringBuilder sb = new StringBuilder();
String[] value = new String[1];
Cacheable cacheable = method.getAnnotation(Cacheable.class);
if (cacheable != null) {
value = cacheable.value();
}
CachePut cachePut = method.getAnnotation(CachePut.class);
if (cachePut != null) {
value = cachePut.value();
}
CacheEvict cacheEvict = method.getAnnotation(CacheEvict.class);
if (cacheEvict != null) {
value = cacheEvict.value();
}
sb.append(value[0]);
//获取参数值
for (Object obj : params) {
sb.append(":" + obj.toString());
}
return sb.toString();
}
};
}
/**
* 实例化 CacheManager 对象,指定使用RedisCacheManager作缓存管理
*
* @return CacheManager
*/
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
// 设置缓存过期时间(单位:秒),60秒
rcm.setDefaultExpiration(600);
return rcm;
}
/**
* 实例化 RedisTemplate 对象
*
* @return RedisTemplate
*/
@Bean
public RedisTemplate redisTemplate() {
RedisTemplate redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
initDomainRedisTemplate(redisTemplate);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
/**
* 设置数据存入 redis 的序列化方式
* redisTemplate 序列化默认使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类
*
* @param redisTemplate
*/
private void initDomainRedisTemplate(
RedisTemplate redisTemplate) {
// 使用Jackson2JsonRedisSerialize 替换默认序列化
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.setKeySerializer(new StringRedisSerializer());
//value乱码问题:Jackson2JsonRedisSerializer
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
}
/**
* redis数据操作异常处理
* 这里的处理:在日志中打印出错误信息,但是放行
* 保证redis服务器出现连接等问题的时候不影响程序的正常运行,使得能够出问题时不用缓存
*
* @return
*/
@Bean
public CacheErrorHandler errorHandler() {
CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException e,
Cache cache, Object key) {
logger.error("redis异常:key=[{}]", key, e);
}
@Override
public void handleCachePutError(RuntimeException e,
Cache cache, Object key, Object value) {
logger.error("redis异常:key=[{}]", key, e);
}
@Override
public void handleCacheEvictError(RuntimeException e,
Cache cache, Object key) {
logger.error("redis异常:key=[{}]", key, e);
}
@Override
public void handleCacheClearError(RuntimeException e,
Cache cache) {
logger.error("redis异常:", e);
}
};
return cacheErrorHandler;
}
/**
* 实例化 ValueOperations 对象,可以使用 String 操作
*
* @param redisTemplate
* @return
*/
@Bean
public ValueOperations valueOperations(
RedisTemplate redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* 实例化 HashOperations 对象,可以使用 Hash 类型操作
*
* @param redisTemplate
* @return
*/
@Bean
public HashOperations hashOperations(
RedisTemplate redisTemplate) {
return redisTemplate.opsForHash();
}
/**
* 实例化 ListOperations 对象,可以使用 List 操作
*
* @param redisTemplate
* @return
*/
@Bean
public ListOperations listOperations(
RedisTemplate redisTemplate) {
return redisTemplate.opsForList();
}
/**
* 实例化 SetOperations 对象,可以使用 Set 操作
*
* @param redisTemplate
* @return
*/
@Bean
public SetOperations setOperations(
RedisTemplate redisTemplate) {
return redisTemplate.opsForSet();
}
/**
* 实例化 ZSetOperations 对象,可以使用 ZSet 操作
*
* @param redisTemplate
* @return
*/
@Bean
public ZSetOperations zSetOperations(
RedisTemplate redisTemplate) {
return redisTemplate.opsForZSet();
}
}
如上写完配置类,在使用时,直接注入:
@Autowired
JedisCluster jedisCluster;