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); }