Jedis 是Redis 的Java用戶端,通過一段時間的使用,jedis基本實現redis的所有功能,並且jedis在用戶端實現redis資料分區功能,Redis本身是沒有資料分布功能。 一、下載jedis 代碼
jedis 代碼地址:https://github.com/xetorthio/jedis
再次感受到開源的強大。呵呵,大家有時間可以看看源碼。 二、項目中如何使用Jedis使用
現在大家都喜歡用maven作為專案管理利器,那我只說明一下Maven如何使用jedis,只需要添加以下依賴就可以。
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.1.0</version> </dependency>
OK, 用maven管理jar包依賴真的很方便。建議大家都採用maven管理項目。 三、建立一個簡單的串連
public class JedisUtil { public static Jedis createJedis() { Jedis jedis = new Jedis("127.0.0.1"); return jedis; } public static Jedis createJedis(String host, int port) { Jedis jedis = new Jedis(host, port); return jedis; } public static Jedis createJedis(String host, int port, String passwrod) { Jedis jedis = new Jedis(host, port); if (!StringUtils.isNotBlank(passwrod)) jedis.auth(passwrod); return jedis; }}
建立一個簡單Jedis對象就是這樣,告訴它的IP地址和連接埠號碼就可以,如果redis有密碼,那需要在建立串連時,需要調用auth方法設定密碼。
當然,簡單串連不適合真實的環境使用,需要有串連池支援 。
四、建立Jedis串連池
建立串連jedis 串連池,jedis 提供JedisPool對象,使用比較方便。jedis pool 是基於apache common pool 實現。
package cn.opensv.example.redis;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;public class JedisPoolUtils { private static JedisPool pool; /** * 建立串連池 真實環境,一般把配置參數缺抽取出來。 * */ private static void createJedisPool() { // 建立串連池配置參數 JedisPoolConfig config = new JedisPoolConfig(); // 設定最大串連數 config.setMaxActive(100); // 設定最大阻塞時間,記住是毫秒數milliseconds config.setMaxWait(1000); // 設定空間串連 config.setMaxIdle(10); // 建立串連池 pool = new JedisPool(config, "127.0.0.1", 6379); } /** * 在多線程環境同步初始化 */ private static synchronized void poolInit() { if (pool == null) createJedisPool(); } /** * 擷取一個jedis 對象 * * @return */ public static Jedis getJedis() { if (pool == null) poolInit(); return pool.getResource(); } /** * 歸還一個串連 * * @param jedis */ public static void returnRes(Jedis jedis) { pool.returnResource(jedis); }}
五、Jedis 實現分區
Jedis分區採用Hash演算法和基於的Key模式比對。Jedis定義一個Hash介面,如果覺得內建的不爽,可以自己實現一個Hash演算法。Jedis內建的Hash的演算法是MurmurHash 2.0 。
MurmurHash演算法:高運算效能,低碰撞率,由Austin Appleby建立於2008年,現已應用到Hadoop、libstdc++、nginx、libmemcached等開源系統。2011年Appleby被Google僱傭,隨後Google推出其變種的CityHash演算法。
官方網站:https://sites.google.com/site/murmurhash/
MurmurHash演算法,自稱超級快的hash演算法,是FNV的4-5倍。
/** * 建立分區對象 * @return */ public