Jedisはredisの5大種類の操作コードに対して詳しく説明します

24966 ワード

この記事では、文字列、リスト、ハッシュ、集合、秩序化集合の5つのタイプの操作について説明します.
JedisUtil
ここでのテスト例はjunit 4を用いて実行され、準備コードは以下の通りである.

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 maps = new HashMap();
	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 
 

キー操作

@Test public void testKey() throws InterruptedException
  {
    System.out.println("    :"+jedis.flushDB());
    System.out.println("         :"+jedis.exists("username"));
    System.out.println("      :"+jedis.set("username", "zzh"));
    System.out.println(jedis.exists("name"));
    System.out.println("      :"+jedis.set("password", "password"));
    System.out.print("         :");
    Set 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
      :OK
false
      :OK
         :[username, password]
   password:1
   password    :false
   username      5s:1
   username       :3
   username     :1
   username       :-1
   username        :string

文字列アクション
Redisでは、文字列は3つのタイプの値を格納できます.
バイト列整数浮動小数点数バイト列

@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));
}

出力結果:

===========    ===========
OK
OK
OK
   key2:1
   key2:null
  key1:OK
  key1  :value1Changed
 key3     :9
key3  :value3End
       :OK
       :[value01, value02, value03]
       :[value01, value02, value03, null]
       :2
       :[null, null, value03]
===========            ==============
1
1
0
value1
value2
===========            =============
OK
value3
null
===========    ,     ==========
value2
key2GetSet
  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  :1
key2  :2
key1   1:2
  key1  :2
key2   1:1
  key2  :1
 key1      5:7
  key1  :7
 key2      5:-4
  key2  :-4

redis 2.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]
===============================
        :1
collections   :[TreeMap, TreeSet, HashSet, LinkedHashMap, WeakHashMap, Stack, Vector, ArrayList]
    0-3       :OK
collections   :[TreeMap, TreeSet, HashSet, LinkedHashMap]
collections    (  ):TreeMap
collections   :[TreeSet, HashSet, LinkedHashMap]
collections    ,     , lpush   :4
collections   :[TreeSet, HashSet, LinkedHashMap, EnumMap]
collections    (  ):EnumMap
collections   :[TreeSet, HashSet, LinkedHashMap]
  collections    1   :OK
collections   :[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.sadd("eleSet", "e6"));
   System.out.println("eleSet      :"+jedis.smembers("eleSet"));
   System.out.println("      e0:"+jedis.srem("eleSet", "e0"));
   System.out.println("eleSet      :"+jedis.smembers("eleSet"));
   System.out.println("      e7 e6:"+jedis.srem("eleSet", "e7","e6"));
   System.out.println("eleSet      :"+jedis.smembers("eleSet"));
   System.out.println("             :"+jedis.spop("eleSet"));
   System.out.println("             :"+jedis.spop("eleSet"));
   System.out.println("eleSet      :"+jedis.smembers("eleSet"));
   System.out.println("eleSet        :"+jedis.scard("eleSet"));
   System.out.println("e3   eleSet :"+jedis.sismember("eleSet", "e3"));
   System.out.println("e1   eleSet :"+jedis.sismember("eleSet", "e1"));
   System.out.println("e1   eleSet :"+jedis.sismember("eleSet", "e5"));
   System.out.println("=================================");
   System.out.println(jedis.sadd("eleSet1", "e1","e2","e4","e3","e0","e8","e7","e5"));
   System.out.println(jedis.sadd("eleSet2", "e1","e2","e4","e3","e0","e8"));
   System.out.println(" eleSet1   e1   eleSet3 :"+jedis.smove("eleSet1", "eleSet3", "e1"));
   System.out.println(" eleSet1   e2   eleSet3 :"+jedis.smove("eleSet1", "eleSet3", "e2"));
   System.out.println("eleSet1    :"+jedis.smembers("eleSet1"));
   System.out.println("eleSet3    :"+jedis.smembers("eleSet3"));
   System.out.println("============    =================");
   System.out.println("eleSet1    :"+jedis.smembers("eleSet1"));
   System.out.println("eleSet2    :"+jedis.smembers("eleSet2"));
   System.out.println("eleSet1 eleSet2   :"+jedis.sinter("eleSet1","eleSet2"));
   System.out.println("eleSet1 eleSet2   :"+jedis.sunion("eleSet1","eleSet2"));
   System.out.println("eleSet1 eleSet2   :"+jedis.sdiff("eleSet1","eleSet2"));//eleSet1  ,eleSet2   
 }

出力結果:

============        ============
8
1
0
eleSet      :[e3, e4, e1, e2, e0, e8, e7, e6, e5]
      e0:1
eleSet      :[e3, e4, e1, e2, e8, e7, e6, e5]
      e7 e6:2
eleSet      :[e3, e4, e1, e2, e8, e5]
             :e5
             :e2
eleSet      :[e3, e4, e1, e8]
eleSet        :4
e3   eleSet :true
e1   eleSet :true
e1   eleSet :false
=================================
8
6
 eleSet1   e1   eleSet3 :1
 eleSet1   e2   eleSet3 :1
eleSet1    :[e3, e4, e0, e8, e7, e5]
eleSet3    :[e1, e2]
============    =================
eleSet1    :[e3, e4, e0, e8, e7, e5]
eleSet2    :[e3, e4, e1, e2, e0, e8]
eleSet1 eleSet2   :[e3, e4, e0, e8]
eleSet1 eleSet2   :[e3, e4, e1, e2, e0, e8, e7, e5]
eleSet1 eleSet2   :[e7, e5]

Setについては、srandmember、sdiffstore、sinterstore、sunionstoreなど、他のコマンドもあります.
ハッシュ#ハッシュ#

@Test public void testHash()
  {
    jedis.flushDB();
    Map map = new HashMap<>();
    map.put("key1","value1");
    map.put("key2","value2");
    map.put("key3","value3");
    map.put("key4","value4");
    jedis.hmset("hash",map);
    jedis.hset("hash", "key5", "value5");
    System.out.println("  hash       :"+jedis.hgetAll("hash"));//return Map
    System.out.println("  hash     :"+jedis.hkeys("hash"));//return Set
    System.out.println("  hash     :"+jedis.hvals("hash"));//return List
    System.out.println(" key6          ,  key6      key6:"+jedis.hincrBy("hash", "key6", 6));
    System.out.println("  hash       :"+jedis.hgetAll("hash"));
    System.out.println(" key6          ,  key6      key6:"+jedis.hincrBy("hash", "key6", 3));
    System.out.println("  hash       :"+jedis.hgetAll("hash"));
    System.out.println("           :"+jedis.hdel("hash", "key2"));
    System.out.println("  hash       :"+jedis.hgetAll("hash"));
    System.out.println("  hash       :"+jedis.hlen("hash"));
    System.out.println("  hash     key2:"+jedis.hexists("hash","key2"));
    System.out.println("  hash     key3:"+jedis.hexists("hash","key3"));
    System.out.println("  hash   :"+jedis.hmget("hash","key3"));
    System.out.println("  hash   :"+jedis.hmget("hash","key3","key4"));
  }

出力結果:

  hash       :{key4=value4, key3=value3, key5=value5, key2=value2, key1=value1}
  hash     :[key4, key3, key5, key2, key1]
  hash     :[value4, value3, value1, value2, value5]
 key6          ,  key6      key6:6
  hash       :{key4=value4, key3=value3, key6=6, key5=value5, key2=value2, key1=value1}
 key6          ,  key6      key6:9
  hash       :{key4=value4, key3=value3, key6=9, key5=value5, key2=value2, key1=value1}
           :1
  hash       :{key4=value4, key3=value3, key6=9, key5=value5, key1=value1}
  hash       :5
  hash     key2:false
  hash     key3:true
  hash   :[value3]
  hash   :[value3, value4]

ちくじしゅうごう

@Test public void testSortedSet()
  {
    jedis.flushDB();
    Map map = new HashMap<>();
    map.put(1.2,"key2");
    map.put(4.0, "key3");
    map.put(5.0,"key4");
    map.put(0.2,"key5");
    System.out.println(jedis.zadd("zset", 3,"key1"));
    System.out.println(jedis.zadd("zset",map));
    System.out.println("zset      :"+jedis.zrange("zset", 0, -1));
    System.out.println("zset      :"+jedis.zrangeWithScores("zset", 0, -1));
    System.out.println("zset      :"+jedis.zrangeByScore("zset", 0,100));
    System.out.println("zset      :"+jedis.zrangeByScoreWithScores("zset", 0,100));
    System.out.println("zset key2   :"+jedis.zscore("zset", "key2"));
    System.out.println("zset key2   :"+jedis.zrank("zset", "key2"));
    System.out.println("  zset    key3:"+jedis.zrem("zset", "key3"));
    System.out.println("zset      :"+jedis.zrange("zset", 0, -1));
    System.out.println("zset      :"+jedis.zcard("zset"));
    System.out.println("zset    1-4        :"+jedis.zcount("zset", 1, 4));
    System.out.println("key2     5:"+jedis.zincrby("zset", 5, "key2"));
    System.out.println("key3     4:"+jedis.zincrby("zset", 4, "key3"));
    System.out.println("zset      :"+jedis.zrange("zset", 0, -1));
  }

出力結果:

1
4
zset      :[key5, key2, key1, key3, key4]
zset      :[[[107, 101, 121, 53],0.2], [[107, 101, 121, 50],1.2], [[107, 101, 121, 49],3.0], [[107, 101, 121, 51],4.0], [[107, 101, 121, 52],5.0]]
zset      :[key5, key2, key1, key3, key4]
zset      :[[[107, 101, 121, 53],0.2], [[107, 101, 121, 50],1.2], [[107, 101, 121, 49],3.0], [[107, 101, 121, 51],4.0], [[107, 101, 121, 52],5.0]]
zset key2   :1.2
zset key2   :1
  zset    key3:1
zset      :[key5, key2, key1, key4]
zset      :4
zset    1-4        :2
key2     5:6.2
key3     4:4.0
zset      :[key5, key1, key3, key4, key2]

整列セットにはzinterstore,zunionstore,zremrangebyscore,zremrangebyscore,zremrangebyscore,zrevrank,zrevrange,zrangebyscoreなどのコマンドもあります.
ソートsort

@Test public void testSort()
 {
   jedis.flushDB();
   jedis.lpush("collections", "ArrayList", "Vector", "Stack", "HashMap", "WeakHashMap", "LinkedHashMap");
   System.out.println("collections   :"+jedis.lrange("collections", 0, -1));
   SortingParams sortingParameters = new SortingParams();
   System.out.println(jedis.sort("collections",sortingParameters.alpha()));
   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", sortingParameters.asc()));
   System.out.println("  :"+jedis.sort("sortedList", sortingParameters.desc()));
   System.out.println("===============================");
   jedis.lpush("userlist", "33"); 
   jedis.lpush("userlist", "22"); 
   jedis.lpush("userlist", "55"); 
   jedis.lpush("userlist", "11"); 
   jedis.hset("user:66", "name", "66"); 
   jedis.hset("user:55", "name", "55"); 
   jedis.hset("user:33", "name", "33"); 
   jedis.hset("user:22", "name", "79"); 
   jedis.hset("user:11", "name", "24"); 
   jedis.hset("user:11", "add", "beijing"); 
   jedis.hset("user:22", "add", "shanghai"); 
   jedis.hset("user:33", "add", "guangzhou"); 
   jedis.hset("user:55", "add", "chongqing"); 
   jedis.hset("user:66", "add", "xi'an"); 
   sortingParameters = new SortingParams();
   sortingParameters.get("user:*->name"); 
   sortingParameters.get("user:*->add"); 
   System.out.println(jedis.sort("userlist",sortingParameters));
 }

出力結果:

collections   :[LinkedHashMap, WeakHashMap, HashMap, Stack, Vector, ArrayList]
[ArrayList, HashMap, LinkedHashMap, Stack, Vector, WeakHashMap]
===============================
sortedList   :[4, 7, 0, 2, 6, 3]
  :[0, 2, 3, 4, 6, 7]
  :[7, 6, 4, 3, 2, 0]
===============================
[24, beijing, 79, shanghai, 33, guangzhou, 55, chongqing]

まとめ
以上がJedisのredisに対する5つの操作コードの詳細な説明のすべてであり、皆さんの役に立つことを望んでいます.興味のある方は引き続き当駅を参照してください.
redis実装カウンタ-ブラシ防止方法の紹介
Redisの主従同期解析
Javaプログラミングredisson実装分散ロックコードの例
不足点があれば、コメントを歓迎します.