通過前一篇《redis的簡單使用》的簡單介紹,本篇主要闡述Jedis對redis的五大類型的操作:字串、列表、散列、集合、有序集合。 JedisUtil
這裡的測試案例採用junit4進行運行,準備代碼如下:
private static final String ipAddr = "10.10.195.112"; private static final int port = 6379; private static Jedis jedis= null; @BeforeClass public static void init() { jedis = JedisUtil.getInstance().getJedis(ipAddr, port); } @AfterClass public static void close() { JedisUtil.getInstance().closeJedis(jedis,ipAddr, port); }
其中JedisUtil是對jedis做的簡單封裝,代碼如下:
import org.apache.log4j.Logger;import java.util.HashMap;import java.util.Map;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;public class JedisUtil{ private Logger logger = Logger.getLogger(this.getClass().getName()); private JedisUtil(){} private static class RedisUtilHolder{ private static final JedisUtil instance = new JedisUtil(); } public static JedisUtil getInstance(){ return RedisUtilHolder.instance; } private static Map<String,JedisPool> maps = new HashMap<String,JedisPool>(); private static JedisPool getPool(String ip, int port){ String key = ip+":"+port; JedisPool pool = null; if(!maps.containsKey(key)) { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxActive(RedisConfig.MAX_ACTIVE); config.setMaxIdle(RedisConfig.MAX_IDLE); config.setMaxWait(RedisConfig.MAX_WAIT); config.setTestOnBorrow(true); config.setTestOnReturn(true); pool = new JedisPool(config,ip,port,RedisConfig.TIMEOUT); maps.put(key, pool); } else { pool = maps.get(key); } return pool; } public Jedis getJedis(String ip, int port) { Jedis jedis = null; int count = 0; do { try { jedis = getPool(ip,port).getResource(); } catch (Exception e) { logger.error("get redis master1 failed!",e); getPool(ip,port).returnBrokenResource(jedis); } } while(jedis == null && count<RedisConfig.RETRY_NUM); return jedis; } public void closeJedis(Jedis jedis, String ip, int port){ if(jedis != null) { getPool(ip,port).returnResource(jedis); } }}public class RedisConfig{ //可用串連執行個體的最大數目,預設值為8; //如果賦值為-1,則表示不限制;如果pool已經分配了maxActive個jedis執行個體,則此時pool的狀態為exhausted(耗盡)。 public static int MAX_ACTIVE = 1024; //控制一個pool最多有多少個狀態為idle(閒置)的jedis執行個體,預設值也是8。 public static int MAX_IDLE = 200; //等待可用串連的最大時間,單位毫秒,預設值為-1,表示永不逾時。如果超過等待時間,則直接拋出JedisConnectionException; public static int MAX_WAIT = 10000; public static int TIMEOUT = 10000; public static int RETRY_NUM = 5;}
鍵操作
@Test public void testKey() throws InterruptedException { System.out.println("清空資料:"+jedis.flushDB()); System.out.println("判斷某個鍵是否存在:"+jedis.exists("username")); System.out.println("新增<'username','zzh'>的索引值對:"+jedis.set("username", "zzh")); System.out.println(jedis.exists("name")); System.out.println("新增<'password','password'>的索引值對:"+jedis.set("password", "password")); System.out.print("系統中所有的鍵如下:"); Set<String> keys = jedis.keys("*"); System.out.println(keys); System.out.println("刪除鍵password:"+jedis.del("password")); System.out.println("判斷鍵password是否存在:"+jedis.exists("password")); System.out.println("設定鍵username的到期時間為5s:"+jedis.expire("username", 5)); TimeUnit.SECONDS.sleep(2); System.out.println("查看鍵username的剩餘存留時間:"+jedis.ttl("username")); System.out.println("移除鍵username的存留時間:"+jedis.persist("username")); System.out.println("查看鍵username的剩餘存留時間:"+jedis.ttl("username")); System.out.println("查看鍵username所儲存的值的類型:"+jedis.type("username")); }
輸出結果:
清空資料:OK判斷某個鍵是否存在:false新增<'username','zzh'>的索引值對:OKfalse新增<'password','password'>的索引值對:OK系統中所有的鍵如下:[username, password]刪除鍵password:1判斷鍵password是否存在:false設定鍵username的到期時間為5s:1查看鍵username的剩餘存留時間:3移除鍵username的存留時間:1查看鍵username的剩餘存留時間:-1查看鍵username所儲存的值的類型:string
字串操作
在Redis裡面,字串可以儲存三種類型的值: 位元組串(byte string) 整數 浮點數 位元組串
@Test public void testString() throws InterruptedException { jedis.flushDB(); System.out.println("===========增加資料==========="); System.out.println(jedis.set("key1","value1")); System.out.println(jedis.set("key2","value2")); System.out.println(jedis.set("key3", "value3")); System.out.println("刪除鍵key2:"+jedis.del("key2")); System.out.println("擷取鍵key2:"+jedis.get("key2")); System.out.println("修改key1:"+jedis.set("key1", "value1Changed")); System.out.println("擷取key1的值:"+jedis.get("key1")); System.out.println("在key3後面加入值:"+jedis.append("key3", "End")); System.out.println("key3的值:"+jedis.get("key3")); System.out.println("增加多個索引值對:"+jedis.mset("key01","value01","key02","value02","key03","value03")); System.out.println("擷取多個索引值對:"+jedis.mget("key01","key02","key03")); System.out.println("擷取多個索引值對:"+jedis.mget("key01","key02","key03","key04")); System.out.println("刪除多個索引值對:"+jedis.del(new String[]{"key01","key02"})); System.out.println("擷取多個索引值對:"+jedis.mget("key01","key02","key03")); jedis.flushDB(); System.out.println("===========新增索引值對防止覆蓋原先值=============="); System.out.println(jedis.setnx("key1", "value1")); System.out.println(jedis.setnx("key2", "value2")); System.out.println(jedis.setnx("key2", "value2-new")); System.out.println(jedis.get("key1")); System.out.println(jedis.get("key2")); System.out.println("===========新增索引值對並設定有效時間============="); System.out.println(jedis.setex("key3", 2, "value3")); System.out.println(jedis.get("key3")); TimeUnit.SECONDS.sleep(3); System.out.println(jedis.get("key3")); System.out.println("===========擷取原值,更新為新值==========");//GETSET is an atomic set this value and return the old value command. System.out.println(jedis.getSet("key2", "key2GetSet")); System.out.println(jedis.get("key2")); System.out.println("獲得key2的值的字串:"+jedis.getrange("key2", 2, 4)); }
輸出結果:
===========增加資料===========OKOKOK刪除鍵key2:1擷取鍵key2:null修改key1:OK擷取key1的值:value1Changed在key3後面加入值:9key3的值:value3End增加多個索引值對:OK擷取多個索引值對:[value01, value02, value03]擷取多個索引值對:[value01, value02, value03, null]刪除多個索引值對:2擷取多個索引值對:[null, null, value03]===========新增索引值對防止覆蓋原先值==============110value1value2===========新增索引值對並設定有效時間=============OKvalue3null===========擷取原值,更新為新值==========value2key2GetSet獲得key2的值的字串:y2G
memcached和redis同樣有append的操作,但是memcached有prepend的操作,redis中並沒有。 整數和浮點數
@Test public void testNumber() { jedis.flushDB(); jedis.set("key1", "1"); jedis.set("key2", "2"); jedis.set("key3", "2.3"); System.out.println("key1的值:"+jedis.get("key1")); System.out.println("key2的值:"+jedis.get("key2")); System.out.println("key1的值加1:"+jedis.incr("key1")); System.out.println("擷取key1的值:"+jedis.get("key1")); System.out.println("key2的值減1:"+jedis.decr("key2")); System.out.println("擷取key2的值:"+jedis.get("key2")); System.out.println("將key1的值加上整數5:"+jedis.incrBy("key1", 5)); System.out.println("擷取key1的值:"+jedis.get("key1")); System.out.println("將key2的值減去整數5:"+jedis.decrBy("key2", 5)); System.out.println("擷取key2的值:"+jedis.get("key2")); }
輸出結果:
key1的值:1key2的值:2key1的值加1:2擷取key1的值:2key2的值減1:1擷取key2的值:1將key1的值加上整數5:7擷取key1的值:7將key2的值減去整數5:-4擷取key2的值:-4
在redis2.6或以上版本中有這個命令:incrbyfloat,即將鍵儲存的值加上浮點數amount,jedis-2.1.0中不支援這一操作。 列表
@Test public void testList(){ jedis.flushDB(); System.out.println("===========添加一個list==========="); jedis.lpush("collections", "ArrayList", "Vector", "Stack", "HashMap", "WeakHashMap", "LinkedHashMap"); jedis.lpush("collections", "HashSet"); jedis.lpush("collections", "TreeSet"); jedis.lpush("collections", "TreeMap"); System.out.println("collections的內容:"+jedis.lrange("collections", 0, -1));//-1代表倒數第一個元素,-2代表倒數第二個元素 System.out.println("collections區間0-3的元素:"+jedis.lrange("collections",0,3)); System.out.println("==============================="); // 刪除列表指定的值 ,第二個參數為刪除的個數(有重複時),後add進去的值先被刪,類似於出棧 System.out.println("刪除指定元素個數:"+jedis.lrem("collections", 2, "HashMap")); System.out.println("collections的內容:"+jedis.lrange("collections", 0, -1)); System.out.println("刪除下表0-3區間之外的元素:"+jedis.ltrim("collections", 0, 3)); System.out.println("collections的內容:"+jedis.lrange("collections", 0, -1)); System.out.println("collections列表出棧(左端):"+jedis.lpop("collections")); System.out.println("collections的內容:"+jedis.lrange("collections", 0, -1)); System.out.println("collections添加元素,從列表右端,與lpush相對應:"+jedis.rpush("collections", "EnumMap")); System.out.println("collections的內容:"+jedis.lrange("collections", 0, -1)); System.out.println("collections列表出棧(右端):"+jedis.rpop("collections")); System.out.println("collections的內容:"+jedis.lrange("collections", 0, -1)); System.out.println("修改collections指定下標1的內容:"+jedis.lset("collections", 1, "LinkedArrayList")); System.out.println("collections的內容:"+jedis.lrange("collections", 0, -1)); System.out.println("==============================="); System.out.println("collections的長度:"+jedis.llen("collections")); System.out.println("擷取collections下標為2的元素:"+jedis.lindex("collections", 2)); System.out.println("==============================="); jedis.lpush("sortedList", "3","6","2","0","7","4"); System.out.println("sortedList排序前:"+jedis.lrange("sortedList", 0, -1)); System.out.println(jedis.sort("sortedList")); System.out.println("sortedList排序後:"+jedis.lrange("sortedList", 0, -1));}
輸出結果:
===========添加一個list===========collections的內容:[TreeMap, TreeSet, HashSet, LinkedHashMap, WeakHashMap, HashMap, Stack, Vector, ArrayList]collections區間0-3的元素:[TreeMap, TreeSet, HashSet, LinkedHashMap]===============================刪除指定元素個數:1collections的內容:[TreeMap, TreeSet, HashSet, LinkedHashMap, WeakHashMap, Stack, Vector, ArrayList]刪除下表0-3區間之外的元素:OKcollections的內容:[TreeMap, TreeSet, HashSet, LinkedHashMap]collections列表出棧(左端):TreeMapcollections的內容:[TreeSet, HashSet, LinkedHashMap]collections添加元素,從列表右端,與lpush相對應:4collections的內容:[TreeSet, HashSet, LinkedHashMap, EnumMap]collections列表出棧(右端):EnumMapcollections的內容:[TreeSet, HashSet, LinkedHashMap]修改collections指定下標1的內容:OKcollections的內容:[TreeSet, LinkedArrayList, LinkedHashMap]===============================collections的長度:3擷取collections下標為2的元素:LinkedHashMap===============================sortedList排序前:[4, 7, 0, 2, 6, 3][0, 2, 3, 4, 6, 7]sortedList排序後:[4, 7, 0, 2, 6, 3]
Redis中還有阻塞式的列表彈出命令以及在列表之間移動元素的命令:blpop, brpop, rpoplpush, brpoplpush等。 集合(Set)
@Test public void testSet() { jedis.flushDB(); System.out.println("============向集合中添加元素============"); System.out.println(jedis.sadd("eleSet", "e1","e2","e4","e3","e0","e8","e7","e5")); System.out.println(jedis.sadd("eleSet", "e6")); System.out.println(jedis