This is the 16th day of my participation in the Gwen Challenge

Start Redis

Go to the Redis folder and run the following command to start Redis

src/redis-server ./redis.conf
Copy the code

Connect to the client after startup

src/redis-cli
Copy the code

Something like 127.0.0.1:6379> will appear, indicating success.

Second, redis data type

Redis has five data types, as follows

  • String: String
  • List the List:
  • Set the Set:
  • Hash: Hash
  • Sorted Set: an ordered Set
  • Base of HyperLogLog:

Data type use

(1) String

Assignment command

set key value
Copy the code

The values command

Get key // Obtain the value of the key and then assign the value. Return the original value getSet key corresponding to keyCopy the code

The delete command

del key
Copy the code
@Test public void testStringCommand() { @SuppressWarnings("resource") ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml"); @SuppressWarnings("unchecked") RedisTemplate<String, String> redisTemplate = applicationContext.getBean(RedisTemplate.class); / / set the value redisTemplate. OpsForValue (). The set (" key1 ", "value1"); redisTemplate.opsForValue().set("key2", "value2"); / / value obtained through key String value1. = (String) redisTemplate opsForValue () get (" key1 "); System.out.println(value1); Redistemplate. delete("key1"); / / for the length of the Long length = redisTemplate. OpsForValue (). The size (" key2 "); System.out.println(length); / / to set a new value and returns the old value String oldValue = redisTemplate. OpsForValue () getAndSet (" key2 ", "newValue"); System.out.println(oldValue); String value2 = redisTemplate.opsForValue().get("key2"); System.out.println(value2); . / / o String String rangeValue = redisTemplate opsForValue () get (" key2 ", 0, 3); System.out.println(rangeValue); / / append a string to the end, return a new string length int newLen = redisTemplate. OpsForValue () append (" key2 ", "append"); System.out.println(newLen); value2 = redisTemplate.opsForValue().get("key2"); System.out.println(value2); }Copy the code

Add or subtract command

  • Incr key: increments the value corresponding to the key by 1. If no current variable is defined, initialize the current variable to 0 and then increments the value by 1.
  • Decr key: the value corresponding to the key is reduced by 1. If no current variable is defined, the current variable is initialized to 0, and then the value is reduced by 1.
  • Incrby key increment: Increments the value corresponding to the key. If no current variable is defined, the current variable is initialized to 0 and then increment is performed.
  • Decr Key increment: Increments the value corresponding to the key. If no current variable is defined, the current variable is initialized to 0 and then increment is performed.

An error is reported if the above operation is performed on a string that cannot be converted to a numeric type.

(error) ERR value is not an integer or out of range
Copy the code

@suppressWarnings ("unchecked") @test public void testNumberCommand() {// Loading the configuration file @SuppressWarnings("resource") ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml"); / / for instance @ SuppressWarnings (" rawtypes ") RedisTemplate rt = applicationContext. GetBean (RedisTemplate. Class); rt.opsForValue().set("i","9"); printCurrValue(rt,"i"); rt.opsForValue().increment("i", 1); printCurrValue(rt,"i"); // RedisTemplate does not support subtraction, so use the following code instead, the original value must be an integer, Rt.getconnectionfactory ().getConnection().decr(rt.getKeySerializer().serialize(" I ")); printCurrValue(rt,"i"); rt.getConnectionFactory().getConnection().decrBy(rt.getKeySerializer().serialize("i"), 6); printCurrValue(rt,"i"); Rt. OpsForValue (). The increment (" I ", 2.3); printCurrValue(rt,"i"); } /** * Prints the current key value * @param rt * @param key */ public void printCurrValue(@suppressWarnings ("rawtypes") RedisTemplate rt,String key) { String i = (String)rt.opsForValue().get(key); System.out.println(i); }Copy the code

(2) Hash

Like a Map in Java, there are many key-value pairs in an object that are suitable for storing objects, and if memory is large enough, a Redis hash structure can store 2^32-1 key-value pairs (over 4 billion).

package com.codeliu.test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.redis.core.RedisTemplate; /** * Public class HashTest {@suppressWarnings ({"rawtypes", "unchecked", "unused" }) @Test public void testHash() { @SuppressWarnings("resource") ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml"); RedisTemplate rt = applicationContext.getBean(RedisTemplate.class); String key = "hash"; HashMap<String,String> map = new HashMap<>(); map.put("f1", "value1"); map.put("f2", "value2"); // equivalent to the hmset command rt.opsforhash ().putall (key, map); / / equivalent to hset command rt. OpsForHash () put (key, "f3", "6"); printValueForHash(rt,key,"f3"); // equivalent to hexists key field command Boolean exist = rt.opsForhash ().haskey (key, "f3"); System.out.println(exist); // equivalent to the hgetall command Map<String, String> keyvalMap = rt.opsForHash().entries(key); Rt.opsforhash ().increment(key, "f3", 2); printValueForHash(rt,key,"f3"); // equivalent to hincrbyfloat rt.opsForHash().increment(key, "f3", 0.3); printValueForHash(rt,key,"f3"); List<String> List = rt.opsForhash ().values(key); Set<String> set = rt.opsForHash().keys(key); List<String> keyList = new ArrayList<>(); keyList.add("f1"); keyList.add("f2"); List<String> value = rt.opsForHash().multiget (key, keyList); Boolean success = rt.opsForHash().putifAbsent (key, "f4", "value4"); System.out.println(success); Long result = rt.opsForhash ().delete(key, "f1","f2"); System.out.println(result); } /** * returns the hash value of the specified key * @param rt * @param key hash * @param field hashKey */ @suppressWarnings ("rawtypes") private void printValueForHash(RedisTemplate rt, String key, String field) { @SuppressWarnings("unchecked") Object value = rt.opsForHash().get(key, field); System.out.println(value); }}Copy the code

Notice the following

  • The hgetall command returns all key-value pairs and stores them in a map object, considering the impact on the JVM if the hash structure is large.
  • Using rt. OpsForHash (.) putAll (key, map); The hmset () method is the equivalent of executing the hmset command, using map. Since the default serializer is configured to be a string, it will only convert the string to perform the corresponding numeric addition. If another serializer is used, the following command may throw an exception.
org.springframework.data.redis.serializer.SerializationException: Cannot deserialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException: Failed to deserialize payload. Is the byte array a result of corresponding serialization for DefaultDeserializer? ; nested exception is java.io.EOFException at org.springframework.data.redis.serializer.JdkSerializationRedisSerializer.deserialize(JdkSerializationRedisSerializer.ja va:81) at org.springframework.data.redis.core.AbstractOperations.deserializeHashKey(AbstractOperations.java:327) at org.springframework.data.redis.core.AbstractOperations.deserializeHashMap(AbstractOperations.java:279) at org.springframework.data.redis.core.DefaultHashOperations.entries(DefaultHashOperations.java:227) at com.codeliu.test.HashTest.testHash(HashTest.java:39) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206) Caused by: org.springframework.core.serializer.support.SerializationFailedException: Failed to deserialize payload. Is the byte array a result of corresponding serialization for DefaultDeserializer?; nested exception is java.io.EOFException at org.springframework.core.serializer.support.DeserializingConverter.convert(DeserializingConverter.java:78) at org.springframework.core.serializer.support.DeserializingConverter.convert(DeserializingConverter.java:36) at org.springframework.data.redis.serializer.JdkSerializationRedisSerializer.deserialize(JdkSerializationRedisSerializer.ja va:79) ... 27 more Caused by: java.io.EOFException at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2638) at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:3113) at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:854) at java.io.ObjectInputStream.<init>(ObjectInputStream.java:349) at org.springframework.core.ConfigurableObjectInputStream.<init>(ConfigurableObjectInputStream.java:63) at org.springframework.core.ConfigurableObjectInputStream.<init>(ConfigurableObjectInputStream.java:49) at org.springframework.core.serializer.DefaultDeserializer.deserialize(DefaultDeserializer.java:68) at org.springframework.core.serializer.support.DeserializingConverter.convert(DeserializingConverter.java:73) ... 29 moreCopy the code
  • When using large hash structures, consider the size of the returned data to avoid returning too much data and causing JVM memory overflow or Redis performance problems.

(3) Linked-list

Can store multiple strings, in order, capable of storing 2^32-1 nodes (over 4 billion nodes). Redis lists are bidirectional. The efficiency of inserting and deleting elements is high, but the efficiency of searching for elements is low.

Redis linked list commands are divided into left operation and right operation. Left operation means left to right and right operation means right to left.

The command instructions note
push key node1 [node2] …. Add node node1 to the leftmost of the list You can add more than one
rpush key node1 [node2]…. Add node node1 to the far right of the list You can add more than one
lindex key index Reads a node with subscript index Returns the node string, starting at 0
llen key Find the length of the list Returns the number of linked list nodes
lpop key Delete the first node on the left and return it
rpop key Delete the first node on the right and return it
linsert key before|after pivot node Insert a node, node, which can be specified before or after the node with the value pivot If the list does not exist, an error is reported, and if there is no corresponding pivot, -1 is returned on insertion failure
lpushx list node If there is a linked list whose key is list, insert node node as the first node from left to right If the list does not exist, it fails
rpushx list node If there is a linked list whose key is list, insert node node as the last node from left to right If the list does not exist, it fails
lrange list start end Get the node values of list from start to end Contains the values of the start and end subscripts
lrem list count value If count is 0, delete all nodes whose value is equal to value. If count is not 0, take the absolute value of count, assuming abs, and delete a maximum of abs nodes whose value is equal to value from left to right Note that count is an integer
lset key index node Set the index node in the list to node
ltrim key start stop Trim the list so that only the nodes from start to stop are kept and the rest are deleted Nodes containing the subscripts of start and end are retained

Notice the following

  • For large data operations, consider the size of inserts and deletions, as this can be a performance – consuming command and cause the Redis server to stall. Batch operations can be performed on servers that do not allow holdup.

  • These actions list above process commands are not safe, because when we operate these commands, other redis client may be in the same operation list, this will cause the concurrent data safety and consistency problems, in order to overcome these problems, redis command provides a list of jam, they at run time, can give a list lock, To ensure the security of the command to operate the linked list.

Block commands for linked lists

The command instructions note
blpop key timeout Removes and retrieves the first element of the list. If there are no elements in the list, the list is blocked until the wait times out or a popup element is found In contrast to the LPOP command, its operation is process-safe
brpop key timeout Removes and retrieves the last element of the list. If there are no elements in the list, the list is blocked until the wait times out or an eject element is found In contrast to the RPOP command, its operation is process-safe
rpoplpush key src dest Remove the last element of a linked list from left to right and insert it into the leftmost of the list The timeout period cannot be set
brpoplpush key src dest timeout Remove the last element of a linked list from left to right, insert it to the left of the list, and set the timeout You can set the timeout period
package com.codeliu.test; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.redis.connection.RedisListCommands; import org.springframework.data.redis.core.RedisTemplate; * @author liu */ public class ListTest {public void printList(RedisTemplate<String, Long size = rt.opsForList().size(key); List<String> valueList = rt.opsForList().range(key, 0, size); System.out.println(valueList); } @SuppressWarnings({ "resource", "rawtypes", "unchecked", "unused" }) @Test public void testList() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml"); RedisTemplate rt = applicationContext.getBean(RedisTemplate.class); // Delete the list so that we can test rt.delete("lits"); // insert node3 into the list list rt.opsForList().leftpush ("lits", "node3"); List<String> nodeList = new ArrayList<>(); for(int i = 2; i >= 1; i--) { nodeList.add("node" + i); } rt.opsForList().leftpushall ("list", nodeList); // Insert a node from the right rt.opsForList().rightpush ("list", "node4"); String node1 = (String)rt.opsForList().index("list", 0); Long size = rt.opsForList().size("list"); Lpop = (String)rt.opsForList().leftPOP ("list"); lpop = (String)rt.opsForList(). Rpop = (String)rt.opsForList().rightPOP ("list"); Linsert: linsert: linsert: linsert Insert a node before node2 try {rt.getConnectionFactory().getConnection().linsert ("list".getBytes(" utF-8 "), RedisListCommands.Position.BEFORE, "node2".getBytes("utf-8"), "before_node2".getBytes("utf-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } rt.opsForList().leftPushifPresent ("list", "head"); Rt.opsforlist ().rightPushifPresent ("list", "end"); List<String> lits = rt.opsForList().range(" List ", 0, 10); lits = rt.opsForlist (). nodeList.clear(); for(int i = 0; i < 3; i++) { nodeList.add("node"); } rt.opsForList().leftpushall ("list", nodeList); Rt.opsforlist ().remove("list", 3, "node"); rt.opsForList(). Rt.opsforlist ().set("list", 0, "new value1"); PrintList (rt,"list"); }}Copy the code
/** * @suppressWarnings ({"resource", "rawtypes", "unchecked" }) @Test public void testBList() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml"); RedisTemplate rt = applicationContext.getBean(RedisTemplate.class); Rt. delete("list1"); rt.delete("list2"); List list <String> nodeList = new ArrayList<String>(); for(int i = 1; i <= 5; i++) { nodeList.add("node" + i); } rt.opsForList().leftPushAll("list1", nodeList); // Spring uses the parameter timeout as a blocking command, equivalent to blpop, and can set the time parameter rt.opsForlist ().leftpop ("list1", 1, timeUnit.seconds); nodeList.clear(); // initialize list2 for(int I = 1; i<= 3; i++) { nodeList.add("data" + i); } rt.opsForList().leftPushAll("list2", nodeList); Rt.opsforlist ().rightPopAndLeftpush ("list1", "list2"); Rt.opsforlist ().rightPopAndLeftpush ("list1", "list2",1, timeUnit.seconds); PrintList (rt,"list1"); printList(rt,"list2"); }Copy the code

In multi-threaded environment, data consistency can be guaranteed to some extent, but the performance is poor.

(4) Set

The set of Redis is not a linear structure, but a hash table structure, which internally stores and searches data according to the hash molecule. Theoretically, a set can store 2^ 32-1 elements, because of the hash structure, the complexity of insert, delete and search is O(1), pay attention to the following points

  • Each element cannot be repeated, and inserting duplicate elements will fail.
  • The set is unordered.
  • Each element of the collection is a String.

Redis sets can operate on other sets, such as finding the intersection, difference, and union of two or more sets.

The command instructions note
sadd key member1 [member2 member3…] Adds a member to a set whose key is key More than one can be added simultaneously
scard key Count the number of set members whose key is key
sdiff key1 [key2] Find the difference between the two sets If the argument is a single key, all elements of the key are returned
sdiffstore des key1 [key2] According to the rules of sdiff command, find out the difference set of key1 and key2, and then save it in the DES set
sinter key1 [key2] Find the intersection of the sets key1 and key2 If the argument is a single key, all elements of the key are returned
sinterstore des key1 [key2] Follow the rules of the sinter command to find the intersection of the two sets key1 and key2, and then save it to the DES set
sismember key member Check whether member is a member of the set whose key is key Returns 1 if yes, 0 otherwise
smembers key Returns all members of the collection If there is a large amount of data, you need to consider iterative traversal
smove src des member Migrate member from the collection SRC to the collection DES
spop key Randomly pop up an element in the collection Notice the randomness, because the set is unordered
srandmember key [count] Returns one or more elements of the set at random. Count is the total number returned. If it is negative, the absolute value is evaluated first If count is not specified, the default value is 1. If count is greater than or equal to the total number of collections, the entire collection is returned
srem key member1 [member2….] Removes an element from the collection, which can be multiple elements For large collections, it can be used to delete some elements and avoid Redis pauses caused by deleting large amounts of data
sunion key1 [key2] Find the union of two sets If the argument is a single key, redis returns all elements of that key
sunionstore des key1 key2 Run the sunion command to find the union, and then save it to the set with the key des
package com.codeliu.test; import java.util.List; import java.util.Set; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.redis.core.RedisTemplate; /** * public class SetTest {@suppressWarnings ({"resource", "rawtypes", "unchecked", "unused" }) @Test public void testSet() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml"); RedisTemplate rt = applicationContext.getBean(RedisTemplate.class); Set<String> set = null; / / to add elements to list the rt boundSetOps (" characters "). The add (" v1 ", "v2", "v3", "v4", "the v5," "v6"); rt.boundSetOps("set2").add("v0","v2","v4","v6","v8"); Rt.opsforset ().size("set1"); // Set = rt.opsForSet().difference("set1", "set2"); Set = rt.opsforset (). Intersect ("set1", "set2"); Boolean exist = rt.opsForSet().ismember ("set1", "v1"); // Exist = rt.opsForset (). Set = rt.opsForSet().members("set1"); String val = (String)rt.opsForSet().pop("set1"); Val = (String)rt.opsForSet().randomMember("set1"); val = (String)rt.opsForSet().randomMember("set1"); List<String> List = rt.opsForSet().randomMembers("set2", 2L); Rt.opsforset ().remove("set1", "v1"); Rt.opsforset (). Union ("set1","set2"); DifferenceAndStore ("set1", "set2", "diff_set"); differenceAndStore("set1", "set2", "diff_set"); Intersecting sets rt.opsforset ().intersectandStore ("set1", "set2", "inter_set"); // Intersecting sets rt.opsforset ().intersectandStore ("set1", "set2", "inter_set"); Rt.opsforset (). UnionAndStore ("set1", "set2", "union_set"); }}Copy the code

(5) Ordered Set (ZSet)

Ordered sets are similar to unordered sets, except that each element has an extra fraction in addition to its value. A score is a floating point number, of type double, and Redis supports sorting fractions by fractions. As with unordered sets, each element is unique, but the fractions can be the same for different elements. The element is also a String, which is also a hash based storage structure.

An ordered set depends on a key to identify which set it is, and depends on a score to sort it, so values and scores are necessary, and you can sort not only scores, but also values under certain conditions.

The command instructions note
zadd key score1 value1 [score2 value2….] Add one or more members to the ordered collection key If no corresponding key exists, an ordered set of keys is created
zcard key Gets the number of members of an ordered collection
zcount key min max Returns a list of members based on the score Min is the minimum value and Max is the maximum value. By default, min and Max are included in the score. The mathematical interval expression method is adopted
zincrby key increment member Add INCREMENT to the score where the ordered set member value is member
zinterstore desKey numKeys key1 [key2 key3….] Find the intersection of multiple ordered sets and save the result in desKey NumKeys is an integer indicating that there are several ordered sets
zlexcount key min max Find the ordered set key member value in the range of min and Max Redis uses the data interval representation method, “[” indicates that the value is included, “(” indicates that the value is not included
zrange key start stop [withscores] Returns the member by the size of the score (from small to large), adding the start and stop parameters to intercept a segment of the return. If the optional withscores is entered, it is returned with the score. Here, the maximum length of the set is len, so Redis sorts the set to form a subscript from 0 to len-1, and then returns the subscript controlled by start and stop (including start and stop)
zrank key member Find the ranking of ordered sets from smallest to largest The number one is 0 and the number two is 1..
zrangebylex key min max [limit offset count] When Redis evaluates the range set, it will generate subscripts 0 to n, and then return the corresponding member according to the offset and the limited return number count Redis uses the data interval representation method, “[” indicates that the value is included, “(” indicates that the value is not included
zrangebyscore key min max [withscores] [limit offset count] To find the range from small to large depending on the size of the score, withscores and limit refer to the zrange command and zrangebylex By default, min and Max are included in the score. Mathematical interval expression is adopted. If not, add (() before the score. [” is not supported
zremrangebyscore key start stop Delete according to the score interval Sort according to score, delete according to start and stop, Redis uses the expression method of data interval, “[” indicates that the value is included, “(” indicates that the value is not included
zremrangebyrank key start stop Delete according to the score from small to large, counting from 0
zremrangebylex key min max Delete according to the distribution of values
zrevrange key start stop [withscores] Sorted by fraction from largest to smallest, see zrange for parameters Same as zrange, except sorted from largest to smallest
zrevrangebyscore key max min [withscores] Sorted byscore from largest to smallest, see ZrangebyScore It’s the same as ZRangeByScore, except it’s ordered from largest to smallest
zrevrank key member Find the ranking of elements in descending order The first rank is 0, the second is 1….
zscore key member Returns the score value of a member Returns a member’s score
zunionstore desKey numKeys key1 [key2 key3 key4…] Find the union of multiple ordered sets, where numKeys is the number of ordered sets

When using ordered collections of Redis in Spring, note that Spring encapsulates the Range and Limit of element values and scores of ordered collections of Redis.

TypedTuple, which is the internal interface of the ZSetOperations interface, source code as follows

public interface ZSetOperations<K, V> {/** * Typed ZSet tuple. */ public interface TypedTuple<V> extends Comparable<TypedTuple<V>> {// getValue(); // Get the score Double getScore(); }}Copy the code

There is a default implementation class, DefaultTypedTuple, which by default encapsulates the values and scores of ordered collections with scores so that the corresponding values and scores can be read from the class object.

Spring encapsulates not only ordered collection elements, but also ranges and limits, using the internal classes Range and Limit under the interface RedisZSetCommand. Range has a static Range method that can be used to generate a Range object.

package com.codeliu.test; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.redis.connection.RedisZSetCommands.Limit; import org.springframework.data.redis.connection.RedisZSetCommands.Range; import org.springframework.data.redis.core.DefaultTypedTuple; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ZSetOperations.TypedTuple; @author liu / / public class ZSetTest {/** * print a common set * @param set */ private void printSet(Set<String> set) { if(set ! = null && set.isEmpty()) { return ; } Iterator<String> iterator = set.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next() + "\t"); } System.out.println(); } /** * Print TypedTuple set * @param set */ @suppressWarnings ({"rawtypes", "unchecked" }) private void printTypedTuple(Set<TypedTuple> set) { if(set ! = null && set.isEmpty()) { return ; } Iterator iterator = set.iterator(); while(iterator.hasNext()) { TypedTuple<String> val = (TypedTuple<String>)iterator.next(); System.out.println("{value = " + val.getValue() + ",score = " + val.getScore() + "}"); } } @SuppressWarnings({ "resource", "rawtypes", "unchecked", "unused" }) @Test public void testZSet() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml"); RedisTemplate rt = applicationContext.getBean(RedisTemplate.class); Set<TypedTuple> set1 = new HashSet<>(); Set<TypedTuple> set2 = new HashSet<>(); int j = 9; for(int i = 1; i <= 9; i++) { j--; Double score1 = Double. ValueOf (I); Double score1 = Double. String value1 = "x" + i; Double score2 = Double.valueOf(j); String value2 = j % 2 == 1 ? "y" + j : "x" + j; // use the DefaultTypedTuple provided by spring --DefaultTypedTuple TypedTuple t1 = new DefaultTypedTuple(value1, score1); set1.add(t1); TypedTuple t2 = new DefaultTypedTuple(value2, score2); set2.add(t2); } // Insert elements into the ordered set zset1 rt.opsForzSet ().add("zset1", set1); rt.opsForZSet().add("zset2", set2); Long size = null; size = rt.opsForZSet().zCard("zset1"); Size = rt.opsForzset ().count("zset1", 3, 6); Set set = null; String set = rt.opsForzSet ().range("zset1", 1, 5); printSet(set); TypedTuple set = rt.opsForzSet ().rangeWithscores ("zset1", 0, -1); printTypedTuple(set); Inter_zset size = rt.opsForzset ().intersectandStore ("zset1", "zset2", "inter_zset"); inter_zset size = rt.opsForzset ().IntersectandStore ("zset1", "zset2", "inter_zset"); // Range = range.range (); / / than range. Lt (" by 8 "); / / is greater than the range. Gt (" x1 "); set = rt.opsForZSet().rangeByLex("zset1", range); printSet(set); // less than or equal to range.lte("x8"); // greater than or equal to range.gte("x1"); set = rt.opsForZSet().rangeByLex("zset1", range); printSet(set); Limit Limit = limite.limit (); limit.count(4); // restrict the fifth element from the truncation limite.offset (5); Set = rt.opsForzSet ().rangebylex ("zset1", range, limit); printSet(set); Long rank = rt.opsforzset (). Rank ("zset1", "x4"); Long rank = rt.opsforzset (). System.out.println("rank = " + rank); Size = rt.opsForzset ().remove("zset1", "x5","x6"); System.out.println("delete = " + size); Size = rt.opsForzset ().removerange ("zset1", 1, 2); Set = rt.opsForzSet (). RangeWithScores ("zset2", 0, -1); printTypedTuple(set); Size = rt.opsForzset ().remove("zset2", "y5","y3"); System.out.println("size = " + size); Double db1 = rt.opsForzSet (). IncrementScore ("zset1", "x1", 11); rt.opsForZSet().removeRangeByScore("zset1", 1, 2); set = rt.opsForZSet().reverseRangeWithScores("zset2", 1, 10); printTypedTuple(set); }}Copy the code

(6) Cardinality (HyperLogLog)

Cardinality is an algorithm. For example, an English book consists of millions of words, the memory is not enough to store them, but the English words themselves are limited, there are many repeated words in the millions of words, remove the repeated words, the memory is enough to store. For example, if the cardinality set of {1,2,5,7,9,1,5,9} is {1,2,5,7,9}, then the cardinality is 5. The ** cardinality is used to estimate the approximate number of storage units needed to store data. The ** cardinality cannot store elements.

The command instructions note
pfadd key element Adds the specified element to HyperLogLog If the element is already stored, 0 is returned and the addition failed
pfcount key Returns the cardinality value for HyperLogLog
pfmerge desKey key1 [key2 key3….] Merge multiple Hyperloglogs and save them in desKey
package com.codeliu.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.redis.core.RedisTemplate; @author liu */ public class HyperLogLogTest {@suppressWarnings ({"resource", "rawtypes", "unchecked" }) @Test public void testHyperLogLog() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml"); RedisTemplate rt = applicationContext.getBean(RedisTemplate.class); rt.opsForHyperLogLog().add("HyperLogLog", "a", "b", "c", "d", "a"); rt.opsForHyperLogLog().add("HyperLogLog2", "a"); rt.opsForHyperLogLog().add("HyperLogLog2", "z"); Long size = rt.opsForHyperLogLog().size("HyperLogLog"); System.out.println("size = " + size); size = rt.opsForHyperLogLog().size("HyperLogLog2"); System.out.println("size = " + size); rt.opsForHyperLogLog().union("des_key", "HyperLogLog","HyperLogLog2"); size = rt.opsForHyperLogLog().size("des_key"); System.out.println("size = " + size); }}Copy the code