1.添加redis启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.配置文件 application.properties
#redis集群配置
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=300
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=1000
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=300
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=100
# 连接超时时间(毫秒)
spring.redis.timeout=0
spring.redis.commandTimeout=5000
# redis.cluster
spring.redis.cluster.nodes=192.168.240.128:7000,192.168.240.128:7001,192.168.240.128:7002,192.168.240.128:7003,192.168.240.128:7004,192.168.240.128:7005,192.168.240.128:7006,192.168.240.128:7007,192.168.240.128:7008
3.redis集群配置类
package com.plat.springboot.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.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
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.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.xml.sax.ErrorHandler;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@Configuration
@ConditionalOnClass({JedisCluster.class})
@EnableCaching
public class redisConfig extends CachingConfigurerSupport{
private final Logger logger = LoggerFactory.getLogger(redisConfig.class);
@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<HostAndPort> 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);
//创建集群对象
return new JedisCluster(nodes,commandTimeout,jedisPoolConfig);
}
/**
* 设置数据存入redis 的序列化方式
*</br>redisTemplate序列化默认使用的jdkSerializeable,存储二进制字节码,导致key会出现乱码,所以自定义
*序列化类
*
* @paramredisConnectionFactory
*/
@Bean
public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate<Object,Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
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);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
/**
* 注解@Cache key生成规则
*/
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
public Object generate(Object target, Method method,
Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
};
/**
* 注解@Cache的管理器,设置过期时间的单位是秒
*
* @Description:
* @param redisTemplate
* @return
*/
@Bean
public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
Map<String, Long> expires = new HashMap<String, Long>();
expires.put("users", 6000L);
expires.put("city", 600L);
cacheManager.setExpires(expires);
cacheManager.setDefaultExpiration(600); // 设置key-value超时时间
return cacheManager;
}
/**
*配置当redis挂掉或者出现问题时,程序继续向下运行操作数据库查询
*/
@Bean
@Override
public CacheErrorHandler errorHandler() {
CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
@Override
public void handleCachePutError(RuntimeException exception, Cache cache,
Object key, Object value) {
RedisErrorException(exception, key);
}
@Override
public void handleCacheGetError(RuntimeException exception, Cache cache,
Object key) {
RedisErrorException(exception, key);
}
@Override
public void handleCacheEvictError(RuntimeException exception, Cache cache,
Object key) {
RedisErrorException(exception, key);
}
@Override
public void handleCacheClearError(RuntimeException exception, Cache cache) {
RedisErrorException(exception, null);
}
};
return cacheErrorHandler;
}
protected void RedisErrorException(Exception exception,Object key){
logger.error("redis异常:key=[{}]", key, exception);
}
}
4.redis注解开发