This article comprehensively describes the five major data types and usage scenarios of Redis, including complete practical cases. It is recommended to collect!!
Hello, I'm glacier~~
Recently, there are a lot of small partners who have changed jobs in the interview, and the interview situation feedback to me is very different. However, many small partners feedback that most of the questions in the interview can be answered in my CSDN blog. The interview process is still very easy, and finally they get the Offer easily! Hearing this, I'm really happy for my friends!
Today, we are arranging an article on Redis technology dry goods. If the article is a little helpful to you, let's start by praising, collecting, commenting and sharing~~
OK, let's start today's text~~
About Redis
Let's talk about the basics of Redis first.
Key value pair based storage system: dictionary form.
Five data structures: string, hash, list, set and sorted set.
Redis spends most of its time on caching because of its fast speed (in memory database, single thread, single process, and Redis 6.0 supports multithreading. We will talk about the new features of Redis 6.0 in detail later).
Redis usage scenarios
- Cache: String type is the most, followed by hash (Dictionary), and json format is the most used value.
- Count (self increment): number of likes, steps, visits, global count, etc.
- Message queue: list type, first in first out or first in last out, bloom. For this, please refer to an open source framework I wrote. The address is: https://github.com/sunshinelyz/mykit-delay.
- Publish subscribe (observer mode)
- Leaderboard: ordered collection
- Distributed lock: you can refer to what I wrote< [high concurrency] high concurrency distributed lock architecture decryption, not all locks are distributed locks!! >, you can also refer to a distributed lock plug-in I wrote. The link address is: https://github.com/sunshinelyz/mykit-lock.
- Be someone nearby
- Bloom filter
- Statistics on the number of people online (Bitmap), etc
The following usage scenarios are also one of the five big data types:
- BitMaps bitmap: bloom filter is essentially a string
- HyperLogLog: unique value count of ultra small memory. 12kb HyperLogLog is essentially a string
- GEO: the essence of geographic information positioning is an ordered set
Master-slave replication: master server and slave server. Data in Redis can be synchronized from the master server to the slave server.
High availability and distributed:
- After version 2.8, redis sentinel is used to support high availability (as a sentry)
- Distributed is supported after version 3.0
Five data types
String (string)
The string type is binary safe. This means that the redis string can contain any data. For example, jpg images or serialized objects.
String type is the most basic data type of redis. The string value in a redis can be 512M at most.
Hash (hash)
Redis hash is a collection of key value pairs.
Redis hash is a mapping table of field and value of string type. Hash is especially suitable for storing objects.
Similar to map < string, Object > in Java
List
Redis list is a simple string list, sorted by insertion order. You can add an element to lead to the head (left) or tail (right) of the list. The bottom layer is actually a linked list.
Set
Redis Set is an unordered Set of string type. It is implemented through HashTable.
Zset(sorted set)
Redis zset, like set, is also a collection of string elements, and duplicate members are not allowed. The difference is that each element is associated with a score of type double. Redis sorts the members of the collection from small to large through scores. The members of zset are unique, but the score can be repeated.
Use case
Here, in order to let the partners have a clearer understanding of how to use the Java client to operate Redis data, we will use Jedis and JedisCluster to demonstrate how to operate Redis data respectively.
preparation
Jedis dependency packages are introduced through maven.
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> <type>jar</type> <scope>compile</scope> </dependency>
Use of Jedis
Create a Jedis object, the set method stores the key value value, and the get method obtains the value corresponding to the key. It is mainly used for a single redis.
Jedis jedis = new Jedis("192.168.175.100", 6379); jedis.set("Jedis", "Hello Work!"); System.out.println(jedis.get("Jedis")); jedis.close()
Here is a diagram of Jedis class structure using the IDEA editor. It can be seen from the diagram that Jedis inherits BinaryJedis and implements multiple interfaces.
Each interface represents a kind of Redis commands. For example, JedisCommands includes commands such as SET GET, and MultiKeyCommands includes commands such as Mset and mget for multiple keys.
Next, we give the complete test code for Jedis to test the five data types of Redis.
Classification code:
- Get Jedis handle
private static Jedis jedis; static { jedis = new Jedis("192.168.175.100", 6379); jedis.auth("123456"); // I previously configured the permission password in redis configuration, which needs to be set here }
- Key value data
/** * Test key - value data * @throws InterruptedException */ @Test public void testKey() throws InterruptedException { System.out.println("Clear data:"+jedis.flushDB()); System.out.println("Determine whether a key exists:"+jedis.exists("username")); System.out.println("newly added<'username','wukong'>Key value pairs:"+jedis.set("username", "wukong")); System.out.println("Does it exist:"+jedis.exists("name")); System.out.println("newly added<'password','password'>Key value pairs:"+jedis.set("password", "password")); Set<String> keys = jedis.keys("*"); System.out.println("All keys in the system are as follows:"+keys); System.out.println("Delete key password:"+jedis.del("password")); System.out.println("Judgment key password Is there:"+jedis.exists("password")); System.out.println("Set key username The expiration time of is 5 s:"+jedis.expire("username", 5)); TimeUnit.SECONDS.sleep(2); System.out.println("View key username Remaining lifetime of:"+jedis.ttl("username")); System.out.println("Remove key username Lifetime of:"+jedis.persist("username")); System.out.println("View key username Remaining lifetime of:"+jedis.ttl("username")); System.out.println("View key username Type of value stored:"+jedis.type("username")); }
- String operation
/*** * String operation * memcached It has the same append operation as redis, but memcached has the prepend operation, which is not available in redis. * @throws InterruptedException */ @Test public void testString() throws InterruptedException { jedis.flushDB(); System.out.println("===========Add data==========="); System.out.println(jedis.set("key1","value1")); System.out.println(jedis.set("key2","value2")); System.out.println(jedis.set("key3", "value3")); System.out.println("Delete key key2:"+jedis.del("key2")); System.out.println("Get key key2:"+jedis.get("key2")); System.out.println("modify key1:"+jedis.set("key1", "value1Changed")); System.out.println("obtain key1 Value of:"+jedis.get("key1")); System.out.println("stay key3 Add value after:"+jedis.append("key3", "End")); System.out.println("key3 Value of:"+jedis.get("key3")); System.out.println("Add multiple key value pairs:"+jedis.mset("key01","value01","key02","value02","key03","value03")); System.out.println("Get multiple key value pairs:"+jedis.mget("key01","key02","key03")); System.out.println("Get multiple key value pairs:"+jedis.mget("key01","key02","key03","key04")); System.out.println("Delete multiple key value pairs:"+jedis.del(new String[]{"key01","key02"})); System.out.println("Get multiple key value pairs:"+jedis.mget("key01","key02","key03")); jedis.flushDB(); System.out.println("===========Adding a key value pair prevents overwriting the original value=============="); 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("===========Add key value pairs and set effective time============="); 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("===========Get the original value and update it to the new value==========");//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("get key2 String of values:"+jedis.getrange("key2", 2, 4)); }
- Integers and floating point numbers
/*** * Integers and floating point numbers */ @Test public void testNumber() { jedis.flushDB(); jedis.set("key1", "1"); jedis.set("key2", "2"); jedis.set("key3", "2.3"); System.out.println("key1 Value of:"+jedis.get("key1")); System.out.println("key2 Value of:"+jedis.get("key2")); System.out.println("key1 Add 1 to the value of:"+jedis.incr("key1")); System.out.println("obtain key1 Value of:"+jedis.get("key1")); System.out.println("key2 The value of minus 1:"+jedis.decr("key2")); System.out.println("obtain key2 Value of:"+jedis.get("key2")); System.out.println("take key1 Add the integer 5 to the value of:"+jedis.incrBy("key1", 5)); System.out.println("obtain key1 Value of:"+jedis.get("key1")); System.out.println("take key2 Subtract the integer 5 from the value of:"+jedis.decrBy("key2", 5)); System.out.println("obtain key2 Value of:"+jedis.get("key2")); }
- list
/*** * list */ @Test public void testList() { jedis.flushDB(); System.out.println("===========Add a 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 Contents:"+jedis.lrange("collections", 0, -1));//-1 represents the penultimate element, - 2 represents the penultimate element System.out.println("collections Interval 0-3 Elements of:"+jedis.lrange("collections",0,3)); System.out.println("==============================="); // Delete the value specified in the list. The second parameter is the number of deleted values (when there are duplicates). The value add ed later is deleted first, which is similar to out of the stack System.out.println("Delete the specified number of elements:"+jedis.lrem("collections", 2, "HashMap")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("Delete table 0 below-3 Elements outside the interval:"+jedis.ltrim("collections", 0, 3)); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("collections List out of stack (left end):"+jedis.lpop("collections")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("collections Add elements from the right end of the list, and lpush Corresponding:"+jedis.rpush("collections", "EnumMap")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("collections List out of stack (right end):"+jedis.rpop("collections")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("modify collections Specify the contents of subscript 1:"+jedis.lset("collections", 1, "LinkedArrayList")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("==============================="); System.out.println("collections Length of:"+jedis.llen("collections")); System.out.println("obtain collections Elements with subscript 2:"+jedis.lindex("collections", 2)); System.out.println("==============================="); jedis.lpush("sortedList", "3","6","2","0","7","4"); System.out.println("sortedList Before sorting:"+jedis.lrange("sortedList", 0, -1)); System.out.println(jedis.sort("sortedList")); System.out.println("sortedList After sorting:"+jedis.lrange("sortedList", 0, -1)); }
- Set set
/*** * set aggregate */ @Test public void testSet() { jedis.flushDB(); System.out.println("============Add elements to the collection============"); 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 All elements of are:"+jedis.smembers("eleSet")); System.out.println("Delete an element e0: "+jedis.srem("eleSet", "e0")); System.out.println("eleSet All elements of are:"+jedis.smembers("eleSet")); System.out.println("Delete two elements e7 and e6: "+jedis.srem("eleSet", "e7","e6")); System.out.println("eleSet All elements of are:"+jedis.smembers("eleSet")); System.out.println("Randomly remove an element from the collection:"+jedis.spop("eleSet")); System.out.println("Randomly remove an element from the collection:"+jedis.spop("eleSet")); System.out.println("eleSet All elements of are:"+jedis.smembers("eleSet")); System.out.println("eleSet Number of elements contained in:"+jedis.scard("eleSet")); System.out.println("e3 Is it eleSet Medium:"+jedis.sismember("eleSet", "e3")); System.out.println("e1 Is it eleSet Medium:"+jedis.sismember("eleSet", "e1")); System.out.println("e1 Is it eleSet Medium:"+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("take eleSet1 Delete in e1 And deposit eleSet3 Medium:"+jedis.smove("eleSet1", "eleSet3", "e1")); System.out.println("take eleSet1 Delete in e2 And deposit eleSet3 Medium:"+jedis.smove("eleSet1", "eleSet3", "e2")); System.out.println("eleSet1 Elements in:"+jedis.smembers("eleSet1")); System.out.println("eleSet3 Elements in:"+jedis.smembers("eleSet3")); System.out.println("============Set operation================="); System.out.println("eleSet1 Elements in:"+jedis.smembers("eleSet1")); System.out.println("eleSet2 Elements in:"+jedis.smembers("eleSet2")); System.out.println("eleSet1 and eleSet2 Intersection of:"+jedis.sinter("eleSet1","eleSet2")); System.out.println("eleSet1 and eleSet2 Union of:"+jedis.sunion("eleSet1","eleSet2")); System.out.println("eleSet1 and eleSet2 Difference set of:"+jedis.sdiff("eleSet1","eleSet2"));//There are in eleSet1 and not in eleSet2 }
- Hash hash
/*** * hash */ @Test public void testHash() { jedis.flushDB(); Map<String,String> map = new HashMap<String,String>(); 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 hash All key value pairs are:"+jedis.hgetAll("hash"));//return Map<String,String> System.out.println("hash hash All keys for are:"+jedis.hkeys("hash"));//return Set<String> System.out.println("hash hash All values for are:"+jedis.hvals("hash"));//return List<String> System.out.println("take key6 Add an integer to the saved value if key6 Add if it does not exist key6: "+jedis.hincrBy("hash", "key6", 6)); System.out.println("hash hash All key value pairs are:"+jedis.hgetAll("hash")); System.out.println("take key6 Add an integer to the saved value if key6 Add if it does not exist key6: "+jedis.hincrBy("hash", "key6", 3)); System.out.println("hash hash All key value pairs are:"+jedis.hgetAll("hash")); System.out.println("Delete one or more key value pairs:"+jedis.hdel("hash", "key2")); System.out.println("hash hash All key value pairs are:"+jedis.hgetAll("hash")); System.out.println("hash hash Number of middle key value pairs:"+jedis.hlen("hash")); System.out.println("judge hash Exists in key2: "+jedis.hexists("hash","key2")); System.out.println("judge hash Exists in key3: "+jedis.hexists("hash","key3")); System.out.println("obtain hash Values in:"+jedis.hmget("hash","key3")); System.out.println("obtain hash Values in:"+jedis.hmget("hash","key3","key4")); }
- Ordered set
/** * Ordered set */ @Test public void testSortedSet() { jedis.flushDB(); Map<String,Double> map = new HashMap<String,Double>(); map.put("key2",1.2); map.put("key3",4.0); map.put("key4",5.0); map.put("key5",0.2); System.out.println(jedis.zadd("zset", 3,"key1")); System.out.println(jedis.zadd("zset",map)); System.out.println("zset All elements in:"+jedis.zrange("zset", 0, -1)); System.out.println("zset All elements in:"+jedis.zrangeWithScores("zset", 0, -1)); System.out.println("zset All elements in:"+jedis.zrangeByScore("zset", 0,100)); System.out.println("zset All elements in:"+jedis.zrangeByScoreWithScores("zset", 0,100)); System.out.println("zset in key2 Score of:"+jedis.zscore("zset", "key2")); System.out.println("zset in key2 Ranking of:"+jedis.zrank("zset", "key2")); System.out.println("delete zset Elements in key3: "+jedis.zrem("zset", "key3")); System.out.println("zset All elements in:"+jedis.zrange("zset", 0, -1)); System.out.println("zset Number of elements in:"+jedis.zcard("zset")); System.out.println("zset The median score is 1-4 Number of elements between:"+jedis.zcount("zset", 1, 4)); System.out.println("key2 Add 5 to your score:"+jedis.zincrby("zset", 5, "key2")); System.out.println("key3 Add 4 to your score:"+jedis.zincrby("zset", 4, "key3")); System.out.println("zset All elements in:"+jedis.zrange("zset", 0, -1)); }
- sort
/** * sort */ @Test public void testSort() { jedis.flushDB(); jedis.lpush("collections", "ArrayList", "Vector", "Stack", "HashMap", "WeakHashMap", "LinkedHashMap"); System.out.println("collections Contents:"+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 Before sorting:"+jedis.lrange("sortedList", 0, -1)); System.out.println("Ascending order:"+jedis.sort("sortedList", sortingParameters.asc())); System.out.println("Ascending order:"+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)); }
Full code:
package com.binghe.redis; import org.junit.Test; import redis.clients.jedis.Jedis; import redis.clients.jedis.SortingParams; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.TimeUnit; /** * Redis operation in stand-alone environment: one redis server */ public class Standalone { private static Jedis jedis; static { jedis = new Jedis("192.168.175.100", 6379); jedis.auth("123456"); // I previously configured the permission password in redis configuration, which needs to be set here } /** * Test key - value data * @throws InterruptedException */ @Test public void testKey() throws InterruptedException { System.out.println("Clear data:"+jedis.flushDB()); System.out.println("Determine whether a key exists:"+jedis.exists("username")); System.out.println("newly added<'username','wukong'>Key value pairs:"+jedis.set("username", "wukong")); System.out.println("Does it exist:"+jedis.exists("name")); System.out.println("newly added<'password','password'>Key value pairs:"+jedis.set("password", "password")); Set<String> keys = jedis.keys("*"); System.out.println("All keys in the system are as follows:"+keys); System.out.println("Delete key password:"+jedis.del("password")); System.out.println("Judgment key password Is there:"+jedis.exists("password")); System.out.println("Set key username The expiration time of is 5 s:"+jedis.expire("username", 5)); TimeUnit.SECONDS.sleep(2); System.out.println("View key username Remaining lifetime of:"+jedis.ttl("username")); System.out.println("Remove key username Lifetime of:"+jedis.persist("username")); System.out.println("View key username Remaining lifetime of:"+jedis.ttl("username")); System.out.println("View key username Type of value stored:"+jedis.type("username")); } /*** * String operation * memcached It has the same append operation as redis, but memcached has the prepend operation, which is not available in redis. * @throws InterruptedException */ @Test public void testString() throws InterruptedException { jedis.flushDB(); System.out.println("===========Add data==========="); System.out.println(jedis.set("key1","value1")); System.out.println(jedis.set("key2","value2")); System.out.println(jedis.set("key3", "value3")); System.out.println("Delete key key2:"+jedis.del("key2")); System.out.println("Get key key2:"+jedis.get("key2")); System.out.println("modify key1:"+jedis.set("key1", "value1Changed")); System.out.println("obtain key1 Value of:"+jedis.get("key1")); System.out.println("stay key3 Add value after:"+jedis.append("key3", "End")); System.out.println("key3 Value of:"+jedis.get("key3")); System.out.println("Add multiple key value pairs:"+jedis.mset("key01","value01","key02","value02","key03","value03")); System.out.println("Get multiple key value pairs:"+jedis.mget("key01","key02","key03")); System.out.println("Get multiple key value pairs:"+jedis.mget("key01","key02","key03","key04")); System.out.println("Delete multiple key value pairs:"+jedis.del(new String[]{"key01","key02"})); System.out.println("Get multiple key value pairs:"+jedis.mget("key01","key02","key03")); jedis.flushDB(); System.out.println("===========Adding a key value pair prevents overwriting the original value=============="); 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("===========Add key value pairs and set effective time============="); 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("===========Get the original value and update it to the new value==========");//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("get key2 String of values:"+jedis.getrange("key2", 2, 4)); } /*** * Integers and floating point numbers */ @Test public void testNumber() { jedis.flushDB(); jedis.set("key1", "1"); jedis.set("key2", "2"); jedis.set("key3", "2.3"); System.out.println("key1 Value of:"+jedis.get("key1")); System.out.println("key2 Value of:"+jedis.get("key2")); System.out.println("key1 Add 1 to the value of:"+jedis.incr("key1")); System.out.println("obtain key1 Value of:"+jedis.get("key1")); System.out.println("key2 The value of minus 1:"+jedis.decr("key2")); System.out.println("obtain key2 Value of:"+jedis.get("key2")); System.out.println("take key1 Add the integer 5 to the value of:"+jedis.incrBy("key1", 5)); System.out.println("obtain key1 Value of:"+jedis.get("key1")); System.out.println("take key2 Subtract the integer 5 from the value of:"+jedis.decrBy("key2", 5)); System.out.println("obtain key2 Value of:"+jedis.get("key2")); } /*** * list */ @Test public void testList() { jedis.flushDB(); System.out.println("===========Add a 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 Contents:"+jedis.lrange("collections", 0, -1));//-1 represents the penultimate element, - 2 represents the penultimate element System.out.println("collections Interval 0-3 Elements of:"+jedis.lrange("collections",0,3)); System.out.println("==============================="); // Delete the value specified in the list. The second parameter is the number of deleted values (when there are duplicates). The value add ed later is deleted first, which is similar to out of the stack System.out.println("Delete the specified number of elements:"+jedis.lrem("collections", 2, "HashMap")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("Delete table 0 below-3 Elements outside the interval:"+jedis.ltrim("collections", 0, 3)); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("collections List out of stack (left end):"+jedis.lpop("collections")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("collections Add elements from the right end of the list, and lpush Corresponding:"+jedis.rpush("collections", "EnumMap")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("collections List out of stack (right end):"+jedis.rpop("collections")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("modify collections Specify the contents of subscript 1:"+jedis.lset("collections", 1, "LinkedArrayList")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("==============================="); System.out.println("collections Length of:"+jedis.llen("collections")); System.out.println("obtain collections Elements with subscript 2:"+jedis.lindex("collections", 2)); System.out.println("==============================="); jedis.lpush("sortedList", "3","6","2","0","7","4"); System.out.println("sortedList Before sorting:"+jedis.lrange("sortedList", 0, -1)); System.out.println(jedis.sort("sortedList")); System.out.println("sortedList After sorting:"+jedis.lrange("sortedList", 0, -1)); } /*** * set aggregate */ @Test public void testSet() { jedis.flushDB(); System.out.println("============Add elements to the collection============"); 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 All elements of are:"+jedis.smembers("eleSet")); System.out.println("Delete an element e0: "+jedis.srem("eleSet", "e0")); System.out.println("eleSet All elements of are:"+jedis.smembers("eleSet")); System.out.println("Delete two elements e7 and e6: "+jedis.srem("eleSet", "e7","e6")); System.out.println("eleSet All elements of are:"+jedis.smembers("eleSet")); System.out.println("Randomly remove an element from the collection:"+jedis.spop("eleSet")); System.out.println("Randomly remove an element from the collection:"+jedis.spop("eleSet")); System.out.println("eleSet All elements of are:"+jedis.smembers("eleSet")); System.out.println("eleSet Number of elements contained in:"+jedis.scard("eleSet")); System.out.println("e3 Is it eleSet Medium:"+jedis.sismember("eleSet", "e3")); System.out.println("e1 Is it eleSet Medium:"+jedis.sismember("eleSet", "e1")); System.out.println("e1 Is it eleSet Medium:"+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("take eleSet1 Delete in e1 And deposit eleSet3 Medium:"+jedis.smove("eleSet1", "eleSet3", "e1")); System.out.println("take eleSet1 Delete in e2 And deposit eleSet3 Medium:"+jedis.smove("eleSet1", "eleSet3", "e2")); System.out.println("eleSet1 Elements in:"+jedis.smembers("eleSet1")); System.out.println("eleSet3 Elements in:"+jedis.smembers("eleSet3")); System.out.println("============Set operation================="); System.out.println("eleSet1 Elements in:"+jedis.smembers("eleSet1")); System.out.println("eleSet2 Elements in:"+jedis.smembers("eleSet2")); System.out.println("eleSet1 and eleSet2 Intersection of:"+jedis.sinter("eleSet1","eleSet2")); System.out.println("eleSet1 and eleSet2 Union of:"+jedis.sunion("eleSet1","eleSet2")); System.out.println("eleSet1 and eleSet2 Difference set of:"+jedis.sdiff("eleSet1","eleSet2"));//There are in eleSet1 and not in eleSet2 } /*** * hash */ @Test public void testHash() { jedis.flushDB(); Map<String,String> map = new HashMap<String,String>(); 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 hash All key value pairs are:"+jedis.hgetAll("hash"));//return Map<String,String> System.out.println("hash hash All keys for are:"+jedis.hkeys("hash"));//return Set<String> System.out.println("hash hash All values for are:"+jedis.hvals("hash"));//return List<String> System.out.println("take key6 Add an integer to the saved value if key6 Add if it does not exist key6: "+jedis.hincrBy("hash", "key6", 6)); System.out.println("hash hash All key value pairs are:"+jedis.hgetAll("hash")); System.out.println("take key6 Add an integer to the saved value if key6 Add if it does not exist key6: "+jedis.hincrBy("hash", "key6", 3)); System.out.println("hash hash All key value pairs are:"+jedis.hgetAll("hash")); System.out.println("Delete one or more key value pairs:"+jedis.hdel("hash", "key2")); System.out.println("hash hash All key value pairs are:"+jedis.hgetAll("hash")); System.out.println("hash hash Number of middle key value pairs:"+jedis.hlen("hash")); System.out.println("judge hash Exists in key2: "+jedis.hexists("hash","key2")); System.out.println("judge hash Exists in key3: "+jedis.hexists("hash","key3")); System.out.println("obtain hash Values in:"+jedis.hmget("hash","key3")); System.out.println("obtain hash Values in:"+jedis.hmget("hash","key3","key4")); } /** * Ordered set */ @Test public void testSortedSet() { jedis.flushDB(); Map<String,Double> map = new HashMap<String,Double>(); map.put("key2",1.2); map.put("key3",4.0); map.put("key4",5.0); map.put("key5",0.2); System.out.println(jedis.zadd("zset", 3,"key1")); System.out.println(jedis.zadd("zset",map)); System.out.println("zset All elements in:"+jedis.zrange("zset", 0, -1)); System.out.println("zset All elements in:"+jedis.zrangeWithScores("zset", 0, -1)); System.out.println("zset All elements in:"+jedis.zrangeByScore("zset", 0,100)); System.out.println("zset All elements in:"+jedis.zrangeByScoreWithScores("zset", 0,100)); System.out.println("zset in key2 Score of:"+jedis.zscore("zset", "key2")); System.out.println("zset in key2 Ranking of:"+jedis.zrank("zset", "key2")); System.out.println("delete zset Elements in key3: "+jedis.zrem("zset", "key3")); System.out.println("zset All elements in:"+jedis.zrange("zset", 0, -1)); System.out.println("zset Number of elements in:"+jedis.zcard("zset")); System.out.println("zset The median score is 1-4 Number of elements between:"+jedis.zcount("zset", 1, 4)); System.out.println("key2 Add 5 to your score:"+jedis.zincrby("zset", 5, "key2")); System.out.println("key3 Add 4 to your score:"+jedis.zincrby("zset", 4, "key3")); System.out.println("zset All elements in:"+jedis.zrange("zset", 0, -1)); } /** * sort */ @Test public void testSort() { jedis.flushDB(); jedis.lpush("collections", "ArrayList", "Vector", "Stack", "HashMap", "WeakHashMap", "LinkedHashMap"); System.out.println("collections Contents:"+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 Before sorting:"+jedis.lrange("sortedList", 0, -1)); System.out.println("Ascending order:"+jedis.sort("sortedList", sortingParameters.asc())); System.out.println("Ascending order:"+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)); } }
Use of JedisCluster
The jediscluster class diagram is roughly the same as the jedis class diagram, but some commands of jediscluster are unavailable. For example, the BinaryJedisCluster class is invalidated. It is mainly used in clusters.
Next, we give the complete source code for testing the five major data types of Redis using JedisCluster.
Classification code
- Get JedisCluster handle
private static JedisCluster jedis; static { // Add the service node Set collection of the cluster Set<HostAndPort> hostAndPortsSet = new HashSet<HostAndPort>(); // Add node hostAndPortsSet.add(new HostAndPort("192.168.175.100", 7777)); hostAndPortsSet.add(new HostAndPort("192.168.175.100", 8888)); hostAndPortsSet.add(new HostAndPort("192.168.175.101", 7777)); hostAndPortsSet.add(new HostAndPort("192.168.175.101", 8888)); hostAndPortsSet.add(new HostAndPort("192.168.175.102", 7777)); hostAndPortsSet.add(new HostAndPort("192.168.175.102", 8888)); // Jedis connection pool configuration JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); // The maximum number of idle connections is 8 by default jedisPoolConfig.setMaxIdle(100); // The maximum number of connections is 8 by default jedisPoolConfig.setMaxTotal(500); //Minimum number of idle connections, 0 by default jedisPoolConfig.setMinIdle(0); // Gets the maximum number of milliseconds to wait for a connection (if it is set to blockwhenexhausted when blocking). If it times out, throw an exception. It is less than zero: the blocking time is uncertain. The default is - 1 jedisPoolConfig.setMaxWaitMillis(2000); // Set for 2 seconds //validateObject the obtained connection jedisPoolConfig.setTestOnBorrow(true); jedis = new JedisCluster(hostAndPortsSet, jedisPoolConfig); }
- Key value data
/** * Test key:value data * flushDB and keys in the cluster are discarded */ @Test public void testKey() throws InterruptedException { //System.out.println("empty data:" + jedis.flushDB()); System.out.println("Determine whether a key exists:"+jedis.exists("username")); System.out.println("newly added<'username','wukong'>Key value pairs:"+jedis.set("username", "xiaohai")); System.out.println("Does it exist:"+jedis.exists("username")); System.out.println("newly added<'password','password'>Key value pairs:"+jedis.set("password", "123456")); //Set<String> keys = jedis.keys("*"); // System.out.println("all keys in the system are as follows:" + keys); System.out.println("Delete key password:"+jedis.del("password")); System.out.println("Judgment key password Is there:"+jedis.exists("password")); System.out.println("Set key username The expiration time of is 10 s:"+jedis.expire("username", 10)); TimeUnit.SECONDS.sleep(2); // System. Thread sleep for 2 seconds out. Println ("view key username remaining lifetime:" + jedis.ttl("username")); System.out.println("View key username Remaining lifetime of:"+jedis.ttl("username")); System.out.println("Remove key username Lifetime of:"+jedis.persist("username")); System.out.println("View key username Remaining lifetime of:"+jedis.ttl("username")); System.out.println("View key username Type of value stored:"+jedis.type("username")); }
- String operation
/*** * String operation * memcached It has the same append operation as redis, but memcached has the prepend operation, which is not available in redis. * flushDB, keys, del (multiple values) and Mset (multiple values) are discarded in the cluster * @throws InterruptedException */ @Test public void testString() throws InterruptedException { //jedis.flushDB(); System.out.println("===========Add data==========="); System.out.println(jedis.set("key1","value1")); System.out.println(jedis.set("key2","value2")); System.out.println(jedis.set("key3", "value3")); System.out.println("Delete key key2:"+jedis.del("key2")); System.out.println("Get key key2:"+jedis.get("key2")); System.out.println("modify key1:"+jedis.set("key1", "value1Changed")); System.out.println("obtain key1 Value of:"+jedis.get("key1")); System.out.println("stay key3 Add value after:"+jedis.append("key3", "End")); System.out.println("key3 Value of:"+jedis.get("key3")); //The connection will only be made when the command is issued. The connection in the cluster is to a node. It cannot be judged that multiple keys are on a node through the slot corresponding to the crc16 algorithm. Multiple key acquisition and deletion are not supported //System.out.println("add multiple key value pairs:" + jedis.mset("key01","value01","key02","value02"); //System.out.println("get multiple key value pairs:" + jedis.mget("key01","key02","key03")); //System.out.println("get multiple key value pairs:" + jedis.mget("key01","key02","key03","key04"); //System.out.println("delete multiple key value pairs:" + jedis.del(new String[]{"key01","key02"})); //System.out.println("get multiple key value pairs:" + jedis.mget("key01","key02","key03")); //jedis.flushDB(); System.out.println("===========Adding a key value pair prevents overwriting the original value=============="); 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("===========Add key value pairs and set effective time============="); 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("===========Get the original value and update it to the new value==========");//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("get key2 String of values:"+jedis.getrange("key2", 2, 4)); // Equivalent to the second position of the intercepted string - the string at the fourth position }
- Integers and floating point numbers
/*** * Integers and floating point numbers */ @Test public void testNumber() { jedis.set("key1", "1"); jedis.set("key2", "2"); jedis.set("key3", "2.3"); System.out.println("key1 Value of:"+jedis.get("key1")); System.out.println("key2 Value of:"+jedis.get("key2")); System.out.println("key1 Add 1 to the value of:"+jedis.incr("key1")); System.out.println("obtain key1 Value of:"+jedis.get("key1")); System.out.println("key2 The value of minus 1:"+jedis.decr("key2")); System.out.println("obtain key2 Value of:"+jedis.get("key2")); System.out.println("take key1 Add the integer 5 to the value of:"+jedis.incrBy("key1", 5)); System.out.println("obtain key1 Value of:"+jedis.get("key1")); System.out.println("take key2 Subtract the integer 5 from the value of:"+jedis.decrBy("key2", 5)); System.out.println("obtain key2 Value of:"+jedis.get("key2")); System.out.println("key3 Value of:"+jedis.get("key3")); // An error will be reported here because key3 is not an integer and cannot be calculated: redis clients. jedis. exceptions. JedisDataException: ERR value is not an integer or out of range // System. out. Println ("value of key2 minus 1:" + jedis.decr("key3")); }
- list
/*** * list */ @Test public void testList() { System.out.println("===========Add a list==========="); jedis.lpush("collections", "ArrayList", "Vector", "Stack", "HashMap", "WeakHashMap", "LinkedHashMap"); jedis.lpush("collections", "HashSet"); // superposition jedis.lpush("collections", "TreeSet"); // superposition jedis.lpush("collections", "TreeMap"); // superposition System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1));//-1 represents the penultimate element, - 2 represents the penultimate element System.out.println("collections Interval 0-3 Elements of:"+jedis.lrange("collections",0,3)); // First 4 values System.out.println("==============================="); // Delete the value specified in the list. The second parameter is the number of deleted values (when there are duplicates). The value add ed later is deleted first, which is similar to out of the stack System.out.println("Delete the specified number of elements:"+jedis.lrem("collections", 2, "HashMap")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("Delete table 0 below-3 Elements outside the interval:"+jedis.ltrim("collections", 0, 3)); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("collections List out of stack (left end):"+jedis.lpop("collections")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("collections Add elements from the right end of the list, and lpush Corresponding:"+jedis.rpush("collections", "EnumMap")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("collections List out of stack (right end):"+jedis.rpop("collections")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("modify collections Specify the contents of subscript 1:"+jedis.lset("collections", 1, "LinkedArrayList")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("==============================="); System.out.println("collections Length of:"+jedis.llen("collections")); System.out.println("obtain collections Elements with subscript 2:"+jedis.lindex("collections", 2)); System.out.println("==============================="); jedis.lpush("sortedList", "3","6","2","0","7","4"); System.out.println("sortedList Before sorting:"+jedis.lrange("sortedList", 0, -1)); System.out.println(jedis.sort("sortedList")); System.out.println("sortedList After sorting:"+jedis.lrange("sortedList", 0, -1)); }
- Set set
/*** * set aggregate */ @Test public void testSet() { System.out.println("============Add elements to the collection============"); 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")); // Returns 0, which already exists in the collection System.out.println("eleSet All elements of are:"+jedis.smembers("eleSet")); System.out.println("Delete an element e0: "+jedis.srem("eleSet", "e0")); System.out.println("eleSet All elements of are:"+jedis.smembers("eleSet")); System.out.println("Delete two elements e7 and e6: "+jedis.srem("eleSet", "e7","e6")); System.out.println("eleSet All elements of are:"+jedis.smembers("eleSet")); System.out.println("Randomly remove an element from the collection:"+jedis.spop("eleSet")); System.out.println("Randomly remove an element from the collection:"+jedis.spop("eleSet")); System.out.println("eleSet All elements of are:"+jedis.smembers("eleSet")); System.out.println("eleSet Number of elements contained in:"+jedis.scard("eleSet")); System.out.println("e3 Is it eleSet Medium:"+jedis.sismember("eleSet", "e3")); System.out.println("e1 Is it eleSet Medium:"+jedis.sismember("eleSet", "e1")); System.out.println("e5 Is it eleSet Medium:"+jedis.sismember("eleSet", "e5")); // An error will be reported if the cluster coexists: redis clients. jedis. exceptions. JedisClusterException: No way to dispatch this command to Redis Cluster because keys have different slots. // Redis cluster, from the coexistence, intersection and difference of key1 set and key2 set, the two keys may have different slots through crc16 algorithm. /*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("Delete e1 from eleSet1 and save it into eleSet3: "+ jedis.smove (" eleSet1 "," eleSet3 "," e1 "); System.out.println("Delete e2 from eleSet1 and save it into eleSet3: "+ jedis.smove (" eleSet1 "," eleSet3 "," e2 "); System.out.println("eleSet1 Element in: "+ jedis.smembers("eleSet1 ")); System.out.println("eleSet3 Element in: "+ jedis.smembers("eleSet3 "));*/ /*System.out.println("============Set operation ======================); System.out.println("eleSet1 Element in: "+ jedis.smembers("eleSet1 ")); System.out.println("eleSet2 Element in: "+ jedis.smembers("eleSet2 ")); System.out.println("eleSet1 Intersection with eleSet2: "+ jedis.sinter("eleSet1","eleSet2 ")); System.out.println("eleSet1 Union of and eleSet2: "+ jedis.sunion("eleSet1","eleSet2 ")); System.out.println("eleSet1 Difference set of and eleSet2: "+ jedis.sdiff("eleSet1","eleSet2 "));*/ jedis.del("eleSet"); jedis.del("eleSet1"); jedis.del("eleSet2"); jedis.del("eleSet3"); }
- Hash hash
/*** * hash */ @Test public void testHash() { Map<String,String> map = new HashMap<String,String>(); 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 hash All key value pairs are:"+jedis.hgetAll("hash"));//return Map<String,String> System.out.println("hash hash All keys for are:"+jedis.hkeys("hash"));//return Set<String> System.out.println("hash hash All values for are:"+jedis.hvals("hash"));//return List<String> System.out.println("take key6 Add an integer to the saved value if key6 Add if it does not exist key6: "+jedis.hincrBy("hash", "key6", 6)); System.out.println("hash hash All key value pairs are:"+jedis.hgetAll("hash")); System.out.println("take key6 Add an integer to the saved value if key6 Add if it does not exist key6: "+jedis.hincrBy("hash", "key6", 3)); System.out.println("hash hash All key value pairs are:"+jedis.hgetAll("hash")); System.out.println("Delete one or more key value pairs:"+jedis.hdel("hash", "key2")); System.out.println("hash hash All key value pairs are:"+jedis.hgetAll("hash")); System.out.println("hash hash Number of middle key value pairs:"+jedis.hlen("hash")); System.out.println("judge hash Exists in key2: "+jedis.hexists("hash","key2")); System.out.println("judge hash Exists in key3: "+jedis.hexists("hash","key3")); System.out.println("obtain hash Values in:"+jedis.hmget("hash","key3")); System.out.println("obtain hash Values in:"+jedis.hmget("hash","key3","key4")); }
- Ordered set
/** * Ordered set */ @Test public void testSortedSet() { Map<String,Double> map = new HashMap<String,Double>(); map.put("key2",1.2); map.put("key3",4.0); map.put("key4",5.0); map.put("key5",0.2); // Add one or more member elements and their score values to the ordered set key. If a member is already a member of the ordered set, update the score value of the member // The score value can be an integer value or a double precision floating-point number System.out.println(jedis.zadd("zset", 3,"key1")); System.out.println(jedis.zadd("zset",map)); System.out.println("zset All elements in:"+jedis.zrange("zset", 0, -1)); System.out.println("zset All elements in:"+jedis.zrangeWithScores("zset", 0, -1)); System.out.println("zset All elements in:"+jedis.zrangeByScore("zset", 0,100)); System.out.println("zset All elements in:"+jedis.zrangeByScoreWithScores("zset", 0,100)); System.out.println("zset in key2 Score of:"+jedis.zscore("zset", "key2")); System.out.println("zset in key2 Ranking of:"+jedis.zrank("zset", "key2")); System.out.println("delete zset Elements in key3: "+jedis.zrem("zset", "key3")); System.out.println("zset All elements in:"+jedis.zrange("zset", 0, -1)); System.out.println("zset Number of elements in:"+jedis.zcard("zset")); System.out.println("zset The median score is 1-4 Number of elements between:"+jedis.zcount("zset", 1, 4)); System.out.println("key2 Add 5 to your score:"+jedis.zincrby("zset", 5, "key2")); System.out.println("key3 Add 4 to your score:"+jedis.zincrby("zset", 4, "key3")); System.out.println("zset All elements in:"+jedis.zrange("zset", 0, -1)); }
- sort
/** * sort */ @Test public void testSort() { jedis.lpush("collections", "ArrayList", "Vector", "Stack", "HashMap", "WeakHashMap", "LinkedHashMap"); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); SortingParams sortingParameters = new SortingParams(); // When string values are saved in the dataset, you can use ALPHA, which is ascending by default System.out.println("alpha Sort by:" + jedis.sort("collections",sortingParameters.alpha())); System.out.println("==============================="); jedis.lpush("sortedList", "3","6","2","0","7","4"); System.out.println("sortedList Before sorting:"+jedis.lrange("sortedList", 0, -1)); System.out.println("Ascending order:"+jedis.sort("sortedList", sortingParameters.asc())); System.out.println("Descending order:"+jedis.sort("sortedList", sortingParameters.desc())); System.out.println("==============================="); // Split table sorting is not supported under cluster /*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(); // The symbol "- >" is used to split the key name and hash field of the hash table. The format is "key - > field" sortingParameters.get("user:*->name"); sortingParameters.get("user:*->add"); System.out.println(jedis.sort("userlist",sortingParameters));*/ }
Complete code
package com.binghe.redis; import org.junit.Test; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.SortingParams; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /** * Jedis operation in cluster environment */ public class Cluster { private static JedisCluster jedis; static { // Add the service node Set collection of the cluster Set<HostAndPort> hostAndPortsSet = new HashSet<HostAndPort>(); // Add node hostAndPortsSet.add(new HostAndPort("192.168.175.100", 7777)); hostAndPortsSet.add(new HostAndPort("192.168.175.100", 8888)); hostAndPortsSet.add(new HostAndPort("192.168.175.101", 7777)); hostAndPortsSet.add(new HostAndPort("192.168.175.101", 8888)); hostAndPortsSet.add(new HostAndPort("192.168.175.102", 7777)); hostAndPortsSet.add(new HostAndPort("192.168.175.102", 8888)); // Jedis connection pool configuration JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); // The maximum number of idle connections is 8 by default jedisPoolConfig.setMaxIdle(100); // The maximum number of connections is 8 by default jedisPoolConfig.setMaxTotal(500); //Minimum number of idle connections, 0 by default jedisPoolConfig.setMinIdle(0); // Gets the maximum number of milliseconds to wait for a connection (if it is set to blockwhenexhausted when blocking). If it times out, throw an exception. It is less than zero: the blocking time is uncertain. The default is - 1 jedisPoolConfig.setMaxWaitMillis(2000); // Set for 2 seconds //validateObject the obtained connection jedisPoolConfig.setTestOnBorrow(true); jedis = new JedisCluster(hostAndPortsSet, jedisPoolConfig); } /** * Test key:value data * flushDB and keys in the cluster are discarded */ @Test public void testKey() throws InterruptedException { //System.out.println("empty data:" + jedis.flushDB()); System.out.println("Determine whether a key exists:"+jedis.exists("username")); System.out.println("newly added<'username','wukong'>Key value pairs:"+jedis.set("username", "xiaohai")); System.out.println("Does it exist:"+jedis.exists("username")); System.out.println("newly added<'password','password'>Key value pairs:"+jedis.set("password", "123456")); //Set<String> keys = jedis.keys("*"); // System.out.println("all keys in the system are as follows:" + keys); System.out.println("Delete key password:"+jedis.del("password")); System.out.println("Judgment key password Is there:"+jedis.exists("password")); System.out.println("Set key username The expiration time of is 10 s:"+jedis.expire("username", 10)); TimeUnit.SECONDS.sleep(2); // System. Thread sleep for 2 seconds out. Println ("view key username remaining lifetime:" + jedis.ttl("username")); System.out.println("View key username Remaining lifetime of:"+jedis.ttl("username")); System.out.println("Remove key username Lifetime of:"+jedis.persist("username")); System.out.println("View key username Remaining lifetime of:"+jedis.ttl("username")); System.out.println("View key username Type of value stored:"+jedis.type("username")); } /*** * String operation * memcached It has the same append operation as redis, but memcached has the prepend operation, which is not available in redis. * flushDB, keys, del (multiple values) and Mset (multiple values) are discarded in the cluster * @throws InterruptedException */ @Test public void testString() throws InterruptedException { //jedis.flushDB(); System.out.println("===========Add data==========="); System.out.println(jedis.set("key1","value1")); System.out.println(jedis.set("key2","value2")); System.out.println(jedis.set("key3", "value3")); System.out.println("Delete key key2:"+jedis.del("key2")); System.out.println("Get key key2:"+jedis.get("key2")); System.out.println("modify key1:"+jedis.set("key1", "value1Changed")); System.out.println("obtain key1 Value of:"+jedis.get("key1")); System.out.println("stay key3 Add value after:"+jedis.append("key3", "End")); System.out.println("key3 Value of:"+jedis.get("key3")); //The connection will only be made when the command is issued. The connection in the cluster is to a node. It cannot be judged that multiple keys are on a node through the slot corresponding to the crc16 algorithm. Multiple key acquisition and deletion are not supported //System.out.println("add multiple key value pairs:" + jedis.mset("key01","value01","key02","value02"); //System.out.println("get multiple key value pairs:" + jedis.mget("key01","key02","key03")); //System.out.println("get multiple key value pairs:" + jedis.mget("key01","key02","key03","key04"); //System.out.println("delete multiple key value pairs:" + jedis.del(new String[]{"key01","key02"})); //System.out.println("get multiple key value pairs:" + jedis.mget("key01","key02","key03")); //jedis.flushDB(); System.out.println("===========Adding a key value pair prevents overwriting the original value=============="); 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("===========Add key value pairs and set effective time============="); 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("===========Get the original value and update it to the new value==========");//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("get key2 String of values:"+jedis.getrange("key2", 2, 4)); // Equivalent to the second position of the intercepted string - the string at the fourth position } /*** * Integers and floating point numbers */ @Test public void testNumber() { jedis.set("key1", "1"); jedis.set("key2", "2"); jedis.set("key3", "2.3"); System.out.println("key1 Value of:"+jedis.get("key1")); System.out.println("key2 Value of:"+jedis.get("key2")); System.out.println("key1 Add 1 to the value of:"+jedis.incr("key1")); System.out.println("obtain key1 Value of:"+jedis.get("key1")); System.out.println("key2 The value of minus 1:"+jedis.decr("key2")); System.out.println("obtain key2 Value of:"+jedis.get("key2")); System.out.println("take key1 Add the integer 5 to the value of:"+jedis.incrBy("key1", 5)); System.out.println("obtain key1 Value of:"+jedis.get("key1")); System.out.println("take key2 Subtract the integer 5 from the value of:"+jedis.decrBy("key2", 5)); System.out.println("obtain key2 Value of:"+jedis.get("key2")); System.out.println("key3 Value of:"+jedis.get("key3")); // An error will be reported here because key3 is not an integer and cannot be calculated: redis clients. jedis. exceptions. JedisDataException: ERR value is not an integer or out of range // System. out. Println ("value of key2 minus 1:" + jedis.decr("key3")); } /*** * list */ @Test public void testList() { System.out.println("===========Add a list==========="); jedis.lpush("collections", "ArrayList", "Vector", "Stack", "HashMap", "WeakHashMap", "LinkedHashMap"); jedis.lpush("collections", "HashSet"); // superposition jedis.lpush("collections", "TreeSet"); // superposition jedis.lpush("collections", "TreeMap"); // superposition System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1));//-1 represents the penultimate element, - 2 represents the penultimate element System.out.println("collections Interval 0-3 Elements of:"+jedis.lrange("collections",0,3)); // First 4 values System.out.println("==============================="); // Delete the value specified in the list. The second parameter is the number of deleted values (when there are duplicates). The value add ed later is deleted first, which is similar to out of the stack System.out.println("Delete the specified number of elements:"+jedis.lrem("collections", 2, "HashMap")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("Delete table 0 below-3 Elements outside the interval:"+jedis.ltrim("collections", 0, 3)); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("collections List out of stack (left end):"+jedis.lpop("collections")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("collections Add elements from the right end of the list, and lpush Corresponding:"+jedis.rpush("collections", "EnumMap")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("collections List out of stack (right end):"+jedis.rpop("collections")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("modify collections Specify the contents of subscript 1:"+jedis.lset("collections", 1, "LinkedArrayList")); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); System.out.println("==============================="); System.out.println("collections Length of:"+jedis.llen("collections")); System.out.println("obtain collections Elements with subscript 2:"+jedis.lindex("collections", 2)); System.out.println("==============================="); jedis.lpush("sortedList", "3","6","2","0","7","4"); System.out.println("sortedList Before sorting:"+jedis.lrange("sortedList", 0, -1)); System.out.println(jedis.sort("sortedList")); System.out.println("sortedList After sorting:"+jedis.lrange("sortedList", 0, -1)); } /*** * set aggregate */ @Test public void testSet() { System.out.println("============Add elements to the collection============"); 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")); // Returns 0, which already exists in the collection System.out.println("eleSet All elements of are:"+jedis.smembers("eleSet")); System.out.println("Delete an element e0: "+jedis.srem("eleSet", "e0")); System.out.println("eleSet All elements of are:"+jedis.smembers("eleSet")); System.out.println("Delete two elements e7 and e6: "+jedis.srem("eleSet", "e7","e6")); System.out.println("eleSet All elements of are:"+jedis.smembers("eleSet")); System.out.println("Randomly remove an element from the collection:"+jedis.spop("eleSet")); System.out.println("Randomly remove an element from the collection:"+jedis.spop("eleSet")); System.out.println("eleSet All elements of are:"+jedis.smembers("eleSet")); System.out.println("eleSet Number of elements contained in:"+jedis.scard("eleSet")); System.out.println("e3 Is it eleSet Medium:"+jedis.sismember("eleSet", "e3")); System.out.println("e1 Is it eleSet Medium:"+jedis.sismember("eleSet", "e1")); System.out.println("e5 Is it eleSet Medium:"+jedis.sismember("eleSet", "e5")); // An error will be reported if the cluster coexists: redis clients. jedis. exceptions. JedisClusterException: No way to dispatch this command to Redis Cluster because keys have different slots. // Redis cluster, from the coexistence, intersection and difference of key1 set and key2 set, the two keys may have different slots through crc16 algorithm. /*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("Delete e1 from eleSet1 and save it into eleSet3: "+ jedis.smove (" eleSet1 "," eleSet3 "," e1 "); System.out.println("Delete e2 from eleSet1 and save it into eleSet3: "+ jedis.smove (" eleSet1 "," eleSet3 "," e2 "); System.out.println("eleSet1 Element in: "+ jedis.smembers("eleSet1 ")); System.out.println("eleSet3 Element in: "+ jedis.smembers("eleSet3 "));*/ /*System.out.println("============Set operation ======================); System.out.println("eleSet1 Element in: "+ jedis.smembers("eleSet1 ")); System.out.println("eleSet2 Element in: "+ jedis.smembers("eleSet2 ")); System.out.println("eleSet1 Intersection with eleSet2: "+ jedis.sinter("eleSet1","eleSet2 ")); System.out.println("eleSet1 Union of and eleSet2: "+ jedis.sunion("eleSet1","eleSet2 ")); System.out.println("eleSet1 Difference set of and eleSet2: "+ jedis.sdiff("eleSet1","eleSet2 "));*/ jedis.del("eleSet"); jedis.del("eleSet1"); jedis.del("eleSet2"); jedis.del("eleSet3"); } /*** * hash */ @Test public void testHash() { Map<String,String> map = new HashMap<String,String>(); 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 hash All key value pairs are:"+jedis.hgetAll("hash"));//return Map<String,String> System.out.println("hash hash All keys for are:"+jedis.hkeys("hash"));//return Set<String> System.out.println("hash hash All values for are:"+jedis.hvals("hash"));//return List<String> System.out.println("take key6 Add an integer to the saved value if key6 Add if it does not exist key6: "+jedis.hincrBy("hash", "key6", 6)); System.out.println("hash hash All key value pairs are:"+jedis.hgetAll("hash")); System.out.println("take key6 Add an integer to the saved value if key6 Add if it does not exist key6: "+jedis.hincrBy("hash", "key6", 3)); System.out.println("hash hash All key value pairs are:"+jedis.hgetAll("hash")); System.out.println("Delete one or more key value pairs:"+jedis.hdel("hash", "key2")); System.out.println("hash hash All key value pairs are:"+jedis.hgetAll("hash")); System.out.println("hash hash Number of middle key value pairs:"+jedis.hlen("hash")); System.out.println("judge hash Exists in key2: "+jedis.hexists("hash","key2")); System.out.println("judge hash Exists in key3: "+jedis.hexists("hash","key3")); System.out.println("obtain hash Values in:"+jedis.hmget("hash","key3")); System.out.println("obtain hash Values in:"+jedis.hmget("hash","key3","key4")); } /** * Ordered set */ @Test public void testSortedSet() { Map<String,Double> map = new HashMap<String,Double>(); map.put("key2",1.2); map.put("key3",4.0); map.put("key4",5.0); map.put("key5",0.2); // Add one or more member elements and their score values to the ordered set key. If a member is already a member of the ordered set, update the score value of the member // The score value can be an integer value or a double precision floating-point number System.out.println(jedis.zadd("zset", 3,"key1")); System.out.println(jedis.zadd("zset",map)); System.out.println("zset All elements in:"+jedis.zrange("zset", 0, -1)); System.out.println("zset All elements in:"+jedis.zrangeWithScores("zset", 0, -1)); System.out.println("zset All elements in:"+jedis.zrangeByScore("zset", 0,100)); System.out.println("zset All elements in:"+jedis.zrangeByScoreWithScores("zset", 0,100)); System.out.println("zset in key2 Score of:"+jedis.zscore("zset", "key2")); System.out.println("zset in key2 Ranking of:"+jedis.zrank("zset", "key2")); System.out.println("delete zset Elements in key3: "+jedis.zrem("zset", "key3")); System.out.println("zset All elements in:"+jedis.zrange("zset", 0, -1)); System.out.println("zset Number of elements in:"+jedis.zcard("zset")); System.out.println("zset The median score is 1-4 Number of elements between:"+jedis.zcount("zset", 1, 4)); System.out.println("key2 Add 5 to your score:"+jedis.zincrby("zset", 5, "key2")); System.out.println("key3 Add 4 to your score:"+jedis.zincrby("zset", 4, "key3")); System.out.println("zset All elements in:"+jedis.zrange("zset", 0, -1)); } /** * sort */ @Test public void testSort() { jedis.lpush("collections", "ArrayList", "Vector", "Stack", "HashMap", "WeakHashMap", "LinkedHashMap"); System.out.println("collections Contents:"+jedis.lrange("collections", 0, -1)); SortingParams sortingParameters = new SortingParams(); // When string values are saved in the dataset, you can use ALPHA, which is ascending by default System.out.println("alpha Sort by:" + jedis.sort("collections",sortingParameters.alpha())); System.out.println("==============================="); jedis.lpush("sortedList", "3","6","2","0","7","4"); System.out.println("sortedList Before sorting:"+jedis.lrange("sortedList", 0, -1)); System.out.println("Ascending order:"+jedis.sort("sortedList", sortingParameters.asc())); System.out.println("Descending order:"+jedis.sort("sortedList", sortingParameters.desc())); System.out.println("==============================="); // Split table sorting is not supported under cluster /*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(); // The symbol "- >" is used to split the key name and hash field of the hash table. The format is "key - > field" sortingParameters.get("user:*->name"); sortingParameters.get("user:*->add"); System.out.println(jedis.sort("userlist",sortingParameters));*/ } }
Remember to like, collect, comment and share~~
Well, that's all for today. I'm glacier. If you have any questions, you can leave a message below to exchange technology, advance together and enter the big factory together~~