java操作redis redis連接池


redis作為緩存型數據庫,越來越受到大家的歡迎,這里簡單介紹一下java如何操作redis。


1、java連接redis

java通過需要jedis的jar包獲取Jedis連接。   

jedis-2.8.0.jar

public void getConn()
{
	//獲取jedis連接
	Jedis jedis = new Jedis("127.0.0.1",6379);
	//獲取redis中以FIELD開頭的key
	Set<String> keys = jedis.keys("FIELD*");
	for(String key : keys)
	{
		System.out.println(key);
	}
}

2、java獲取jedis連接池

如果每次連接redis都new1個Jedis的話,勢必耗費很多資源,這里就提到redis連接池。

所需jar包

commons-pool2-2.3.jar

jedis-2.8.0.jar

public class RedisUtil 
{
	private static JedisPool pool = null;
	
	/**
	 * 獲取jedis連接池
	 * */
	public static JedisPool getPool()
	{
		if(pool == null)
		{
			//創建jedis連接池配置
			JedisPoolConfig config = new JedisPoolConfig();
			//最大連接數
			config.setMaxTotal(100);
			//最大空閑連接
			config.setMaxIdle(5);
			//創建redis連接池
			pool = new JedisPool(config,"127.0.0.1",6379,超時時長);
		}
		return pool;
	}
	
	/**
	 * 獲取jedis連接
	 * */
	public static Jedis getConn()
	{
		return getPool().getResource();
	}
}

新版本jedis的jar包獲取連接池,使用完后用jedis.close()歸還連接:
@Test
	public void testPool()
	{
		//獲取jedis連接
		Jedis jedis = RedisUtil.getConn();	
		String value = jedis.get(key);
		//使用之后記得關閉連接
		jedis.close();
	}


老版本的jedis jar獲取連接,使用完要用pool.returnResource(jedis);歸還連接

public void testPool()
{
	//獲取jedis連接
	JedisPool pool = RedisUtil.getPool();
	Jedis jedis = pool.getResource();
	String value = jedis.get(key);
	//使用之后記得關閉連接
	pool.returnResource(jedis);
}



免責聲明!

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



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