java操作redis redis連線池
阿新 • • 發佈:2018-12-25
redis作為快取型資料庫,越來越受到大家的歡迎,這裡簡單介紹一下java如何操作redis。
1、java連線redis
java通過需要jedis的jar包獲取Jedis連線。
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
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); }