SpringBoot连接Redis集群

1. 依赖

    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
    </dependency>

2. 修改配置文件

server.port=100

#redis集群节点信息
spring.redis.cluster.nodes=192.168.25.132:6379,192.168.25.132:6380,192.168.25.133:6379,192.168.25.133:6380,192.168.25.134:6379,192.168.25.134:6380
#redis连接密码(默认空)
spring.redis.password=
#redis连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=20
#redis连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
#redis连接池最大空闲连接
spring.redis.jedis.pool.max-idle=200
#redis连接池最小空闲连接
spring.redis.jedis.pool.min-idle=20
#redis连接超时时间(毫秒)
spring.redis.timeout=10000

3. 创建RedisClusterConfig

@Configuration
public class RedisClusterConfig {
    
    

    @Value("${spring.redis.cluster.nodes}")
    private String clusterNodes;

    @Value("${spring.redis.database}")
    private int database;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;

    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxActive;

    @Value("${spring.redis.jedis.pool.max-wait}")
    private long maxWait;

    @Bean
    public JedisCluster getJedisCluster() {
    
    
        return new JedisCluster(getNodes(), timeout, poolConfig());
    }

    private JedisPoolConfig poolConfig() {
    
    
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        config.setMaxTotal(maxActive);
        config.setMaxWaitMillis(maxWait);
        return config;
    }

    private Set<HostAndPort> getNodes() {
    
    
        String[] cNodes = clusterNodes.split(",");
        Set<HostAndPort> nodes = new HashSet<HostAndPort>();
        // 分割出集群节点
        String[] hp;
        for (String node : cNodes) {
    
    
            hp = node.split(":");
            nodes.add(new HostAndPort(hp[0], Integer.parseInt(hp[1])));
        }
        return nodes;
    }
}

4. 测试

@RestController
@RequestMapping("/redis/cluster")
public class RedisClusterController {
    
    
    @Autowired
    private JedisCluster jedisCluster;

    @GetMapping("/set")
    public void set(@RequestParam("key") String key, @RequestParam("value") String value){
    
    
        jedisCluster.set(key, value);
    }
}

这边就不演示了,分别访问以下2个地址,能得到结果说明正常:

http://localhost:100/redis/cluster/set?key=name&value=zhangsan

http://localhost:100/redis/cluster/get?key=name

猜你喜欢

转载自blog.csdn.net/qq_28834355/article/details/112852707