SpringBoot java连接Redis集群

本文详细介绍了如何在Spring Boot应用中配置Redis集群,包括配置文件的设置、Java配置类的编写,以及如何通过注解使用Redis缓存,提供了完整的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

集群模式:
配置文件设置:

###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<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);
    // 创建集群对象
    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<String, Object> redisTemplate() {
    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
    redisTemplate.setConnectionFactory(redisConnectionFactory);
    initDomainRedisTemplate(redisTemplate);
    redisTemplate.afterPropertiesSet();
    return redisTemplate;
}

/**
 * 设置数据存入 redis 的序列化方式
 * </br>redisTemplate 序列化默认使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类
 *
 * @param redisTemplate
 */
private void initDomainRedisTemplate(
        RedisTemplate<String, Object> 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<String, Object> valueOperations(
        RedisTemplate<String, Object> redisTemplate) {
    return redisTemplate.opsForValue();
}

/**
 * 实例化 HashOperations 对象,可以使用 Hash 类型操作
 *
 * @param redisTemplate
 * @return
 */
@Bean
public HashOperations<String, String, Object> hashOperations(
        RedisTemplate<String, Object> redisTemplate) {
    return redisTemplate.opsForHash();
}

/**
 * 实例化 ListOperations 对象,可以使用 List 操作
 *
 * @param redisTemplate
 * @return
 */
@Bean
public ListOperations<String, Object> listOperations(
        RedisTemplate<String, Object> redisTemplate) {
    return redisTemplate.opsForList();
}

/**
 * 实例化 SetOperations 对象,可以使用 Set 操作
 *
 * @param redisTemplate
 * @return
 */
@Bean
public SetOperations<String, Object> setOperations(
        RedisTemplate<String, Object> redisTemplate) {
    return redisTemplate.opsForSet();
}

/**
 * 实例化 ZSetOperations 对象,可以使用 ZSet 操作
 *
 * @param redisTemplate
 * @return
 */
@Bean
public ZSetOperations<String, Object> zSetOperations(
        RedisTemplate<String, Object> redisTemplate) {
    return redisTemplate.opsForZSet();
}
}

如上写完配置类,在使用时,直接注入:

@Autowired
JedisCluster jedisCluster;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MichaelYZ111

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值