JedisCluster 基本代码__写给自己看的

本文介绍如何在Spring Boot项目中配置并使用Redis Cluster集群。通过示例代码展示了如何从属性文件读取集群节点信息,并设置连接池参数,最终创建JedisCluster实例。此配置可以作为Spring Boot应用集成Redis集群的基础。

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

pom.xml
<dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
</dependency>
主要代码
Set<HostAndPort> jedisClusterNodes = Sets.newHashSet();
for (String hps : redisProperties.getAddressList()) {
    String[] hp = hps.split(":");
    jedisClusterNodes.add(new HostAndPort(hp[0], Integer.parseInt(hp[1])));
}
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxIdle(redisProperties.getMaxIdle());
config.setMaxTotal(redisProperties.getMaxTotal());
config.setMaxWaitMillis(redisProperties.getMaxWaitMillis());
config.setMinIdle(redisProperties.getMinIdle());
config.setTestWhileIdle(true);
JedisCluster jc = new JedisCluster(jedisClusterNodes, Protocol.DEFAULT_TIMEOUT, config);
return jc;

-----------------------------------用springboot@Bean注入到spring中去
 

import java.util.Set;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.testng.collections.Sets;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.Protocol;

@Configuration
public class RedisTaskConfigurations {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisTaskConfigurations.class);


    @Autowired
    private RedisProperties redisProperties;

    @Bean(name="jedisCluster")
    public JedisCluster getJedisCluster() {
        Set<HostAndPort> jedisClusterNodes = Sets.newHashSet();
        for (String hps : redisProperties.getAddressList()) {
            String[] hp = hps.split(":");
            jedisClusterNodes.add(new HostAndPort(hp[0], Integer.parseInt(hp[1])));
        }
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxIdle(redisProperties.getMaxIdle());
        config.setMaxTotal(redisProperties.getMaxTotal());
        config.setMaxWaitMillis(redisProperties.getMaxWaitMillis());
        config.setMinIdle(redisProperties.getMinIdle());
        config.setTestWhileIdle(true);
        JedisCluster jc = new JedisCluster(jedisClusterNodes, Protocol.DEFAULT_TIMEOUT, config);
        return jc;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值