寫一篇關於redis鏈接池的平常記錄,最近在學習,因此學到的都將記錄下來,首先是寫一個redis鏈接池:java
package com.charRobot.util; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public final class RedisPool { // Redis服務器ip private static String ADDR = "127.0.0.1"; // Redis端口號 private static Integer PORT = 6379; // Redis訪問密碼 private static String AUTH = "password"; //可用鏈接實例的最大數目,默認爲8; //若是賦值爲-1,則表示不限制,若是pool已經分配了maxActive個jedis實例,則此時pool的狀態爲exhausted(耗盡) private static Integer MAX_TOTAL = 1024; //控制一個pool最多有多少個狀態爲idle(空閒)的jedis實例,默認值是8 private static Integer MAX_IDLE = 200; //等待可用鏈接的最大時間,單位是毫秒,默認值爲-1,表示永不超時。 //若是超過等待時間,則直接拋出JedisConnectionException private static Integer MAX_WAIT_MILLIS = 10000; private static Integer TIMEOUT = 10000; //在borrow(用)一個jedis實例時,是否提早進行validate(驗證)操做; //若是爲true,則獲得的jedis實例均是可用的 private static Boolean TEST_ON_BORROW = true; private static JedisPool jedisPool = null; /** * 靜態塊,初始化Redis鏈接池 */ static { try { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(MAX_TOTAL); config.setMaxIdle(MAX_IDLE); config.setMaxWaitMillis(MAX_WAIT_MILLIS); jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH); } catch (Exception e) { e.printStackTrace(); } } /** * 獲取Jedis實例 * * @return */ public synchronized static Jedis getJedis() { try { if (jedisPool != null) { Jedis jedis = jedisPool.getResource(); return jedis; } else { return null; } } catch (Exception e) { e.printStackTrace(); return null; } } public static void returnResource(final Jedis jedis) { if (jedis != null) { jedisPool.returnResource(jedis); } } }
寫好後,咱們直接寫一個main方法,用於測試:redis
public class RedisJava { public static void main(String[] args) { RedisPool.getJedis().set("name", "xlf"); System.out.println("name : " + RedisPool.getJedis().get("name")); } }
運行後獲得結果:服務器
其實用法都差很少,咱們再試試list操做:學習
RedisPool.getJedis().lpush("info","xlf"); RedisPool.getJedis().lpush("info","100"); RedisPool.getJedis().lpush("info","200"); System.out.println("長度" + RedisPool.getJedis().llen("info")); // jedis.llen表示長度,-1表示全部 System.out.println("info:" + RedisPool.getJedis().lrange("info", 0, -1));
運行結果爲:測試
大部分操做都差很少,只是邏輯有所不一樣3d