Java connection sentinel mode redis

import redis.clients.jedis.*;

import java.util.HashSet;
import java.util.Set;

public class JedisSentinelExampleWithPassword {

    public static void main(String[] args) {

        // Redis Sentinel 的主节点名称
        String masterName = "mymaster";

        // Redis Sentinel 的地址和端口
        Set<String> sentinels = new HashSet<>();
        sentinels.add("sentinel1.example.com:26379");
        sentinels.add("sentinel2.example.com:26379");
        sentinels.add("sentinel3.example.com:26379");

        // Redis 的密码
        String password = "mypassword";

        // 使用 JedisSentinelPool 创建连接池,并设置密码
        JedisSentinelPool sentinelPool = new JedisSentinelPool(masterName, sentinels, new JedisPoolConfig(), password);

        // 从连接池中获取 Jedis 连接
        Jedis jedis = sentinelPool.getResource();

        try {
            // 使用 Jedis 进行操作
            jedis.set("key", "value");
            String result = jedis.get("key");
            System.out.println("Result: " + result);
        } finally {
            // 释放 Jedis 连接回连接池
            jedis.close();
        }

        // 关闭连接池
        sentinelPool.close();
    }
}

Guess you like

Origin blog.csdn.net/LONG_Yi_1994/article/details/130202335