使用Jedis提供的Java API對Redis進行操做,是Redis官方推崇的方式;而且,使用Jedis提供的對Redis的支持也最爲靈活、全面;不足之處,就是編碼複雜度較高。redis
[一]. 入門使用:
下載Jedis的依賴包jedis-2.1.0.jar,而後將其添加到classpath下面。而後,便可進行編程:
1. 定義鏈接:Redis暫時不要設置登陸密碼sql
- Jedis jedis = new Jedis("192.168.142.12");
2. 進行鍵值存儲:編程
- jedis.set("country", "China");
3. 獲取value值:緩存
- String country = jedis.get("country");
4. 刪除key: 服務器
- jedis.del("country");
[二]. 使用鏈接池:
1. 添加依賴包commons-pool.jar,注意不要選擇高版本,以避免沒必要要的錯誤。
2. 配置屬性文件:redis.propertiesnosql
- redis.host=192.168.142.12 #Redis服務器地址
- redis.port=6379 #服務端口
- redis.timeout=3000 #超時時間:單位ms
- redis.password=nick123 #受權密碼
- redis.pool.maxActive=200 #最大鏈接數:可以同時創建的「最大連接個數」
- redis.pool.maxIdle=20 #最大空閒數:空閒連接數大於maxIdle時,將進行回收
- redis.pool.minIdle=5 #最小空閒數:低於minIdle時,將建立新的連接
- redis.pool.maxWait=3000 #最大等待時間:單位ms
- redis.pool.testOnBorrow=true #使用鏈接時,檢測鏈接是否成功
- redis.pool.testOnReturn=true #返回鏈接時,檢測鏈接是否成功
3. 加載屬性文件:redis.properties編碼
- ResourceBundle bundle = ResourceBundle.getBundle("redis");
4. 建立配置對象: spa
- JedisPoolConfig config = new JedisPoolConfig();
- String host = bundle.getString("redis.host");
- ...
- config.setMaxActive(Integer.valueOf(bundle.getString("redis.pool.maxActive")));
- ...
- config.setTestOnBorrow(Boolean.valueOf(bundle.getString("redis.pool.testOnBorrow")));
- ...
5. 建立Jedis鏈接池:對象
- JedisPool pool = new JedisPool(config, host, port, timeout, password);
[三]. 使用方式:
1. 從鏈接池獲取Jedis對象:blog
- Jedis jedis = pool.getResource();
2. 基本操做:
- jedis.set("province", "shannxi");
- String province = jedis.get("province");
- jedis.del("province");
3. 將Jedis對象歸還給鏈接池:
- pool.returnResource(jedis);