java客戶端Jedis操作Redis Sentinel 連接池


pom.xml配置

            <dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>1.0.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.7.0</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>        
public class JedisPoolUtil {
	
	private static JedisSentinelPool pool = null;

	public static Properties getJedisProperties() {

		Properties config = new Properties();
		InputStream is = null;
		try {
			is = JedisPoolUtil.class.getClassLoader().getResourceAsStream("cacheConfig.properties");
			config.load(is);
		} catch (IOException e) {
			logger.error("", e);
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					logger.error("", e);
				}
			}
		}
		return config;
	}

	/**
	 * 創建連接池
	 * 
	 */
	private static void createJedisPool() {
		// 建立連接池配置參數
		JedisPoolConfig config = new JedisPoolConfig();
		Properties prop = getJedisProperties();
		// 設置最大連接數
		config.setMaxTotal(StringUtil.nullToInteger(prop.getProperty("MAX_ACTIVE")));
		// 設置最大阻塞時間,記住是毫秒數milliseconds
		config.setMaxWaitMillis(StringUtil.nullToInteger(prop.getProperty("MAX_WAIT")));
		// 設置空間連接
		config.setMaxIdle(StringUtil.nullToInteger(prop.getProperty("MAX_IDLE")));
		// jedis實例是否可用
		boolean borrow = prop.getProperty("TEST_ON_BORROW") == "false" ? false : true;
		config.setTestOnBorrow(borrow);
		// 創建連接池
//		pool = new JedisPool(config, prop.getProperty("ADDR"), StringUtil.nullToInteger(prop.getProperty("PORT")), StringUtil.nullToInteger(prop.getProperty("TIMEOUT")));// 線程數量限制,IP地址,端口,超時時間
		//獲取redis密碼
		String password = StringUtil.nullToString(prop.getProperty("PASSWORD"));

		 String masterName = "mymaster";
		Set<String> sentinels = new HashSet<String>();
		sentinels.add("192.168.137.128:26379");
		sentinels.add("192.168.137.128:26380");
		sentinels.add("192.168.137.128:26381");
		pool = new JedisSentinelPool(masterName, sentinels, config);
	}

	/**
	 * 在多線程環境同步初始化
	 */
	private static synchronized void poolInit() {
		if (pool == null)
			createJedisPool();
	}

	/**
	 * 獲取一個jedis 對象
	 * 
	 * @return
	 */
	public static Jedis getJedis() {
		if (pool == null)
			poolInit();
		return pool.getResource();
	}

	/**
	 * 釋放一個連接
	 * 
	 * @param jedis
	 */
	public static void returnRes(Jedis jedis) {
		pool.returnResource(jedis);
	}

	/**
	 * 銷毀一個連接
	 * 
	 * @param jedis
	 */
	public static void returnBrokenRes(Jedis jedis) {
		pool.returnBrokenResource(jedis);
	}
	
	
	public static void main(String[] args){
		Jedis jedis=getJedis();
		
	}

}

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM