`

redis 哨兵连接池(JedisSentinelPool)——不通过spring

 
阅读更多
import java.util.HashSet;
import java.util.Set;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;


/**
 * 直连JedisSentinelPool
 * 
 */
public class TestRedisSentinel {

	public static void main(String[] args) {
		// 定义sentinel set
		Set<String> sentinels = new HashSet<String>();
		HostAndPort hp1 = new HostAndPort("172.19.59.50", 26379);
		String sentinel1 = hp1.toString();
		sentinels.add(sentinel1);
		HostAndPort hp2 = new HostAndPort("172.19.59.50", 36379);
		String sentinel2 = hp2.toString();
		sentinels.add(sentinel2);
		HostAndPort hp3 = new HostAndPort("172.19.59.50", 46379);
		String sentinel3 = hp3.toString();
		sentinels.add(sentinel3);
		HostAndPort hp4 = new HostAndPort("172.19.59.50", 56379);
		String sentinel4 = hp4.toString();
		sentinels.add(sentinel4);
		
		// 创建JedisSentinelPool对象
		JedisSentinelPool sentinelPool = new JedisSentinelPool("mymaster", sentinels);
		System.out.println("current master: " + sentinelPool.getCurrentHostMaster().toString());
		
		// 使用sentinelPool获取jedis对象
		Jedis master = sentinelPool.getResource();
		// 操作redis
		master.set("username", "test");
		sentinelPool.returnResource(master);
		
		Jedis master2 = sentinelPool.getResource();// 注意:一定要每次重新从pool中取一个连接,否则会一直访问老master。
		String value = master2.get("username");
		System.out.println("username: " + value);
		
		// 销毁jedis对象和sentinelpool
		master2.close();
		sentinelPool.destroy();
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics