步驟:
1 .下載window版本的Redis,解壓到硬碟,啟動Redis伺服器和用戶端
下載地址:http://pan.baidu.com/s/1pLRnhc3
雙擊redis-server.exe可啟動redis伺服器,
雙擊redis-cli.exe開啟redis用戶端,可用來執行儲存等命令。
啟動redis伺服器的時候,會顯示用戶端串連的個數,下面開啟兩個用戶端,進行測試:
2 下載jedis
jedis是Redis基於Java語言的用戶端,我下載的版本是jedis-2.7.2.jar,在實際項目中也可以用maven去管理這些jar包,非常方便。
下載地址:http://pan.baidu.com/s/1gf865l5
下面簡單介紹在java中如何使用redis
1.直接使用jedis
在項目中引入上面下載的jedis的jar包。
package com.test.jedis;import redis.clients.jedis.Jedis;public class JedisTest { public static void main(String[] args) { Jedis jedis=new Jedis("127.0.0.1"); jedis.set("name7","kxl7"); System.out.println("取資料:"+jedis.get("name7")); jedis.del("name7"); System.out.println("刪除後取資料:"+jedis.get("name7")); jedis.close(); }}
輸出結果:
取資料:kxl7刪除後取資料:null
2.使用Jedis串連池
Jedis使用commons-pool完成池化實現,所以需要再引入commons-pool的jar包,我引入的是commons-pool2-2.4.2.jar
package com.test.jedisPool;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;public class JedisPoolUtil { //Redis伺服器IP private static String ADDRESS = "127.0.0.1"; //連接埠號碼 private static int PORT = 6379; //串連池pool裡idle狀態的jedis執行個體個數,預設值也是8。 private static int MAX_IDLE = 100; //當池內沒有返回對象時,最大等待時間(單位毫秒),預設值為-1,表示永不逾時。逾時拋JedisConnectionException異常 private static long MAX_WAIT = 10000; private static int TIME_OUT = 10000; //最大分配的串連數 private static int MAX_TOTAL=200; //當調用borrow Object方法時,是否進行有效性檢查; private static boolean TEST_ON_BORROW = true; //當調用return Object方法時,是否進行有效性檢查 private static boolean TEST_ON_RETURN=true; private static JedisPool jedisPool = null; /** * 初始化Redis串連池 */ static { try { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxIdle(MAX_IDLE); config.setMaxTotal(MAX_TOTAL); config.setMaxWaitMillis(MAX_WAIT); config.setTestOnBorrow(TEST_ON_BORROW); config.setTestOnReturn(TEST_ON_RETURN); jedisPool = new JedisPool(config, ADDRESS, PORT, TIME_OUT); } catch (Exception e) { e.printStackTrace(); } } /** * 擷取Jedis執行個體 */ public static Jedis getJedis() { try { if (jedisPool != null) { Jedis jedisResource = jedisPool.getResource(); return jedisResource; } else { return null; } } catch (Exception e) { e.printStackTrace(); return null; } } /** * 釋放jedis資源 */ public static void close(final Jedis jedis) { if (jedis != null) { jedis.close(); } }}
使用:
public class TestJedisPool { public static void main(String[] args) { Jedis jedis=JedisPoolUtil.getJedis(); jedis.set("name4","kxl4"); System.out.println("取資料:"+jedis.get("name4")); }}
上面JedisPoolUtil類的靜態屬性都可以儲存在設定檔中,方便管理,然後在代碼中讀取設定檔完成池化。