"Spring integration component" redis(Spring Data Redis 2.X)

quick get start

pom dependency

<!-- spring-data-redis (Attention and cluster Also pay attention to the version problem with spring Version of)-->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>2.1.9.RELEASE</version>
</dependency>
<!--2.9.1 There is a connection leak bug-->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.10.2</version>
</dependency>

Jackson's dependency may be used:

<!--Jackson-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.11.4</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.4</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.11.4</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.11.4</version>
</dependency>

How to configure

standalone mode

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class StandaloneRedisConfig {

    /**
     * Configure connection pool
     * @return
     */
    @Bean
    public JedisPoolConfig standalonePoolConfig(){
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        //The maximum number of free links in the connection pool is 20, which means that 20 free links are maintained even if there are no database links
        poolConfig.setMaxIdle(20);
        //Controls how many jedis instances a pool can allocate
        poolConfig.setMaxTotal(300);
        //Maximum waiting time. When there is no available connection, the maximum time that the connection pool waits for the link to be returned is ms. if the time exceeds, an exception will be thrown
        poolConfig.setMaxWaitMillis(1000);
        //Check the validity of the link when obtaining the connection
        poolConfig.setTestOnCreate(true);
        return poolConfig;
    }

    /**
     * redis Stand alone configuration
     * RedisStandaloneConfiguration stand-alone
     * RedisSentinelConfiguration Master slave copy (sentinel mode)
     * RedisClusterConfiguration colony
     * @return
     */
    @Bean
    public RedisStandaloneConfiguration standaloneConfiguration(){
        RedisStandaloneConfiguration standaloneConfiguration = new RedisStandaloneConfiguration();
        standaloneConfiguration.setHostName("127.0.0.1");
        standaloneConfiguration.setPort(6379);
        standaloneConfiguration.setDatabase(0);
        return standaloneConfiguration;
    }

    /**
     * Configure connection factory
     * @return
     */
    @Bean
    public JedisConnectionFactory standaloneConnectionFactory(){
        return new JedisConnectionFactory(standaloneConfiguration());
    }

    /**
     * Configure Redis template
     */
    @Bean
    public RedisTemplate standaloneRedisTemplate(){
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(standaloneConnectionFactory());
        StringRedisSerializer keySerializer = new StringRedisSerializer();
        GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();
        //keySerializer and valueSerializer configure serializers of String type key and value in Redis
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setValueSerializer(valueSerializer);
        //HashKeySerializer and HashValueSerializer configure the serializer of Hash type key and value in Redis
        redisTemplate.setHashKeySerializer(keySerializer);
        redisTemplate.setHashValueSerializer(valueSerializer);
        return redisTemplate;
    }
}

Master slave mode (sentry)

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class SentinelRedisConfig {

    /**
     * Configure connection pool
     * @return
     */
    @Bean
    public JedisPoolConfig sentinelPoolConfig(){
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        //The maximum number of free links in the connection pool is 20, which means that 20 free links are maintained even if there are no database links
        poolConfig.setMaxIdle(20);
        //Controls how many jedis instances a pool can allocate
        poolConfig.setMaxTotal(300);
        //Maximum waiting time. When there is no available connection, the maximum time that the connection pool waits for the link to be returned is ms. if the time exceeds, an exception will be thrown
        poolConfig.setMaxWaitMillis(1000);
        //Check the validity of the link when obtaining the connection
        poolConfig.setTestOnCreate(true);
        return poolConfig;
    }

    /**
     * redis Sentinel mode
     * RedisStandaloneConfiguration stand-alone
     * RedisSentinelConfiguration Master slave copy (sentinel mode)
     * RedisClusterConfiguration colony
     * @return
     */
    @Bean
    public RedisSentinelConfiguration sentinelConfiguration(){
        RedisSentinelConfiguration sentinelConfiguration = new RedisSentinelConfiguration();
        //Master node name
        sentinelConfiguration.setMaster("mymaster");
        //Sentinel monitoring node (one master and two slave)
        List<RedisNode> redisNodeList = new ArrayList();
        redisNodeList.add(new RedisNode("192.168.1.10", 6379));
        redisNodeList.add(new RedisNode("192.168.1.11", 6379));
        redisNodeList.add(new RedisNode("192.168.1.12", 6379));
        sentinelConfiguration.setSentinels(redisNodeList);
        //database
        sentinelConfiguration.setDatabase(0);
        return sentinelConfiguration;
    }

    /**
     * Configure connection factory
     * @return
     */
    @Bean
    public JedisConnectionFactory sentinelConnectionFactory(){
        return new JedisConnectionFactory(sentinelConfiguration());
    }

    /**
     * Configure Redis template
     */
    @Bean
    public RedisTemplate sentinelRedisTemplate(){
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(sentinelConnectionFactory());
        StringRedisSerializer keySerializer = new StringRedisSerializer();
        GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();
        //keySerializer and valueSerializer configure serializers of String type key and value in Redis
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setValueSerializer(valueSerializer);
        //HashKeySerializer and HashValueSerializer configure the serializer of Hash type key and value in Redis
        redisTemplate.setHashKeySerializer(keySerializer);
        redisTemplate.setHashValueSerializer(valueSerializer);
        return redisTemplate;
    }
}

Cluster mode

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;


@Configuration
public class ClusterRedisConfig {
    /**
     * Configure connection pool
     * @return
     */
    @Bean
    public JedisPoolConfig clusterPoolConfig(){
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        //The maximum number of free links in the connection pool is 20, which means that 20 free links are maintained even if there are no database links
        poolConfig.setMaxIdle(20);
        //Controls how many jedis instances a pool can allocate
        poolConfig.setMaxTotal(300);
        //Maximum waiting time. When there is no available connection, the maximum time that the connection pool waits for the link to be returned is ms. if the time exceeds, an exception will be thrown
        poolConfig.setMaxWaitMillis(1000);
        //Check the validity of the link when obtaining the connection
        poolConfig.setTestOnCreate(true);
        return poolConfig;
    }

    /**
     * redis Cluster mode
     * RedisStandaloneConfiguration stand-alone
     * RedisSentinelConfiguration Master slave copy (sentinel mode)
     * RedisClusterConfiguration colony
     * @return
     */
    @Bean
    public RedisClusterConfiguration clusterConfiguration(){
        RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration();
        clusterConfiguration.clusterNode("127.0.0.1", 6380);
        clusterConfiguration.clusterNode("127.0.0.1", 6381);
        clusterConfiguration.clusterNode("127.0.0.1", 6382);
        return clusterConfiguration;
    }

    /**
     * Configure connection factory
     * @return
     */
    @Bean
    public JedisConnectionFactory clusterConnectionFactory(){
        return new JedisConnectionFactory(clusterConfiguration());
    }

    /**
     * Configure Redis template
     */
    @Bean
    public RedisTemplate clusterRedisTemplate(){
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(clusterConnectionFactory());
        StringRedisSerializer keySerializer = new StringRedisSerializer();
        GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();
        //keySerializer and valueSerializer configure serializers of String type key and value in Redis
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setValueSerializer(valueSerializer);
        //HashKeySerializer and HashValueSerializer configure the serializer of Hash type key and value in Redis
        redisTemplate.setHashKeySerializer(keySerializer);
        redisTemplate.setHashValueSerializer(valueSerializer);
        return redisTemplate;
    }
}

1. JedisPoolConfig property configuration

//Whether the connection is blocked when it is exhausted. If false, an exception will be reported. If true, it will block until timeout. The default is true
config.setBlockWhenExhausted(true);
//Set the eviction policy class name, defaultevaluationpolicy by default (when the connection exceeds the maximum idle time, or the number of connections exceeds the maximum number of idle connections)
config.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");
//Whether to enable the jmx (Java Management Extensions) management function of pool. The default value is true
config.setJmxEnabled(true);
//Whether to enable last in first out. The default is true
config.setLifo(true);
//The maximum number of idle connections is 8 by default
config.setMaxIdle(10);
//The maximum number of connections is 8 by default
config.setMaxTotal(50);
//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
config.setMaxWaitMillis(30000);
//The minimum idle time (in milliseconds) of resources in the resource pool. When this value is reached, idle resources will be removed. The default is 1800000 milliseconds (30 minutes)
config.setMinEvictableIdleTimeMillis(60000);
//Minimum number of idle connections, 0 by default
config.setMinIdle(0);
//The maximum number of evictions for each eviction check is 1/abs(n), which is 3 by default
config.setNumTestsPerEvictionRun(3);
//The object is evicted after how long it is idle. When the idle time > this value and the idle connection > the maximum idle number, it is evicted directly. It is no longer judged according to MinEvictableIdleTimeMillis (the default eviction policy)
config.setSoftMinEvictableIdleTimeMillis(1800000);
//Check the validity when obtaining the connection. The default is false
config.setTestOnBorrow(false);
//Whether to enable idle resource monitoring. The default is false
config.setTestWhileIdle(true);
//The detection cycle of idle resources (in milliseconds). If it is negative, the eviction thread will not be run. The default is - 1
config.setTimeBetweenEvictionRunsMillis(-1);

2. RedisStandaloneConfiguration single machine configuration

RedisStandaloneConfiguration standaloneConfiguration = new RedisStandaloneConfiguration();
standaloneConfiguration.setHostName("127.0.0.1");
standaloneConfiguration.setPort(6379);
standaloneConfiguration.setDatabase(0);
standaloneConfiguration.setPassword("123456");

3. RedisSentinelConfiguration master-slave replication

RedisSentinelConfiguration sentinelConfiguration = new RedisSentinelConfiguration();
//Master node name
sentinelConfiguration.setMaster("mymaster");
//Sentinel monitoring node (one master and two slave)
List<RedisNode> redisNodeList = new ArrayList();
redisNodeList.add(new RedisNode("192.168.1.10", 6379));
redisNodeList.add(new RedisNode("192.168.1.11", 6379));
redisNodeList.add(new RedisNode("192.168.1.12", 6379));
sentinelConfiguration.setSentinels(redisNodeList);
//database
sentinelConfiguration.setDatabase(0);
sentinelConfiguration.setPassword("123456");

4. RedisClusterConfiguration cluster configuration

RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration();
clusterConfiguration.clusterNode("127.0.0.1", 6380);
clusterConfiguration.clusterNode("127.0.0.1", 6381);
clusterConfiguration.clusterNode("127.0.0.1", 6382);
clusterConfiguration.setMaxRedirects(100);
clusterConfiguration.setPassword("123456");

5. JedisConnectionFactory connection factory

In spring-data-redis2 Many methods in JedisConnectionFactory above version 0 have expired. It is officially recommended to pass in the configuration object in the constructor:

  • Stand alone configuration} RedisStandaloneConfiguration
  • Master slave replication} RedisSentinelConfiguration
  • Cluster RedisClusterConfiguration

6. Redistemplate redistemplate

(1) Manually set the serialization mode of key and value

Serializer: an object that can serialize the stored key and value. It is a tool similar to converter.

You can implement the incoming java object - > the data type recognized by redis. For example: string.

The default Serializer is StringRedisSerializer.

Set the default serializer as string serializer because redis can store only string and byte arrays.

Generally speaking, the data objects operated in our code are java objects.

If the data carrier used in the code is a string object, is there a problem using Jackson2JsonRedisSerializer as a serializer?

If the version of jackson plug-in is not appropriate and there are potential errors, the string data may be converted to json string - > {chars: [], bytes: []}

Using StringRedisSerializer does not have this problem. It does not handle string conversion. It thinks that the key and value operated in the code are strings.  

test

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={RootConfig.class, WebConfig.class}) //If it is configured by Java Config, specify the relevant configuration class
@WebAppConfiguration
public class ClusterRedisTest {

    @Autowired
    private RedisTemplate clusterRedisTemplate;

    @Test
    public void test(){
        clusterRedisTemplate.opsForValue().set("cluster", "hello");
        System.out.println(clusterRedisTemplate.opsForValue().get("cluster"));
    }
}

RedisTemplate API

Encapsulate the specified key through bound

After specifying, a series of operations are carried out without explicitly specifying the Key again, that is, BoundKeyOperations:

  • BoundValueOperations
  • BoundSetOperations
  • BoundListOperations
  • BoundSetOperations
  • BoundHashOperations
//1. Set the value through redisTemplate
clusterRedisTemplate.boundValueOps("StringKey").set("StringValue");
clusterRedisTemplate.boundValueOps("StringKey").set("StringValue", 1, TimeUnit.MINUTES);
//2. Set values through BoundValueOperations
BoundValueOperations stringKey = clusterRedisTemplate.boundValueOps("StringKey");
stringKey.set("StringValue");
stringKey.set("StringValue", 1, TimeUnit.MINUTES);
//3. Setting values through ValueOperations
ValueOperations ops = clusterRedisTemplate.opsForValue();
ops.set("StringKey", "StringValue");
ops.set("StringValue", "StringValue", 1, TimeUnit.MINUTES);
//1. Get the value through redisTemplate
String str1 = (String) clusterRedisTemplate.boundValueOps("StringKey").get();
//2. Get value through BoundValueOperations
BoundValueOperations stringKey = clusterRedisTemplate.boundValueOps("StringKey");
String str2 = (String) stringKey.get();
//3. Get value through ValueOperations
ValueOperations ops = clusterRedisTemplate.opsForValue();
String str3 = (String) ops.get("StringKey");

Basic API

//Delete key
clusterRedisTemplate.delete(keys);
//Specifies the expiration time of the key
clusterRedisTemplate.expire(key,time,TimeUnit.MINUTES);
//Get expiration time according to key
Long expire = clusterRedisTemplate.getExpire(key);
//Determine whether the key exists
clusterRedisTemplate.hasKey(key);
//Sequential increment
clusterRedisTemplate.boundValueOps("StringKey").increment(3L);
//Sequential decrement
clusterRedisTemplate.boundValueOps("StringKey").increment(-3L);

Hash type related operations

1. Set value

//1. Set the value through redisTemplate
clusterRedisTemplate.boundHashOps("HashKey").put("SmallKey", "HashVaue");
//2. Set values through BoundValueOperations
BoundHashOperations hashKey = clusterRedisTemplate.boundHashOps("HashKey");
hashKey.put("SmallKey", "HashVaue");
//3. Setting values through ValueOperations
HashOperations hashOps = clusterRedisTemplate.opsForHash();
hashOps.put("HashKey", "SmallKey", "HashVaue");

2. Set expiration time (set separately)

clusterRedisTemplate.boundValueOps("HashKey").expire(1,TimeUnit.MINUTES);
clusterRedisTemplate.expire("HashKey",1,TimeUnit.MINUTES);

3. Add a Map collection

HashMap<String, String> hashMap = new HashMap<>();
clusterRedisTemplate.boundHashOps("HashKey").putAll(hashMap);

4. Extract small key s from Hash

//1. Get the value through redisTemplate
Set keys1 = clusterRedisTemplate.boundHashOps("HashKey").keys();
//2. Get value through BoundValueOperations
BoundHashOperations hashKey = clusterRedisTemplate.boundHashOps("HashKey");
Set keys2 = hashKey.keys();
//3. Get value through ValueOperations
HashOperations hashOps = clusterRedisTemplate.opsForHash();
Set keys3 = hashOps.keys("HashKey");

5. Extract all value values

//1. Get the value through redisTemplate
List values1 = clusterRedisTemplate.boundHashOps("HashKey").values();
//2. Get value through BoundValueOperations
BoundHashOperations hashKey = clusterRedisTemplate.boundHashOps("HashKey");
List values2 = hashKey.values();
//3. Get value through ValueOperations
HashOperations hashOps = clusterRedisTemplate.opsForHash();
List values3 = hashOps.values("HashKey");

6. Extract the value value according to the Hash key

//1. Get through redisTemplate
String value1 = (String) clusterRedisTemplate.boundHashOps("HashKey").get("SmallKey");
//2. Get value through BoundValueOperations
BoundHashOperations hashKey = clusterRedisTemplate.boundHashOps("HashKey");
String value2 = (String) hashKey.get("SmallKey");
//3. Get value through ValueOperations
HashOperations hashOps = clusterRedisTemplate.opsForHash();
String value3 = (String) hashOps.get("HashKey", "SmallKey");

7. Gets a collection of all key value pairs

//1. Get through redisTemplate
Map entries = clusterRedisTemplate.boundHashOps("HashKey").entries();
//2. Get value through BoundValueOperations
BoundHashOperations hashKey = clusterRedisTemplate.boundHashOps("HashKey");
Map entries1 = hashKey.entries();
//3. Get value through ValueOperations
HashOperations hashOps = clusterRedisTemplate.opsForHash();
Map entries2 = hashOps.entries("HashKey");

8. Delete

//Delete small key
clusterRedisTemplate.boundHashOps("HashKey").delete("SmallKey");
//Delete large key
clusterRedisTemplate.delete("HashKey");

9. Judge whether the Hash contains this value

Boolean isEmpty = clusterRedisTemplate.boundHashOps("HashKey").hasKey("SmallKey");

Set type related operations

1. Add

//1. Set the value through redisTemplate
clusterRedisTemplate.boundSetOps("setKey").add("setValue1", "setValue2", "setValue3");

//2. Set values through BoundValueOperations
BoundSetOperations setKey = clusterRedisTemplate.boundSetOps("setKey");
setKey.add("setValue1", "setValue2", "setValue3");

//3. Setting values through ValueOperations
SetOperations setOps = clusterRedisTemplate.opsForSet();
setOps.add("setKey", "SetValue1", "setValue2", "setValue3");

2. Set expiration time (set separately)

clusterRedisTemplate.boundValueOps("setKey").expire(1,TimeUnit.MINUTES);
clusterRedisTemplate.expire("setKey",1,TimeUnit.MINUTES);

3. Get all the values in the Set according to the key

//1. Get the value through redisTemplate
Set set1 = clusterRedisTemplate.boundSetOps("setKey").members();

//2. Get value through BoundValueOperations
BoundSetOperations setKey = clusterRedisTemplate.boundSetOps("setKey");
Set set2 = setKey.members();

//3. Get value through ValueOperations
SetOperations setOps = clusterRedisTemplate.opsForSet();
Set set3 = setOps.members("setKey");

4. Query whether value already exists

Boolean isEmpty = clusterRedisTemplate.boundSetOps("setKey").isMember("setValue2");

5. Gets the length of the Set

Long size = clusterRedisTemplate.boundSetOps("setKey").size();

6. Removes the specified element

Long result1 = clusterRedisTemplate.boundSetOps("setKey").remove("setValue1");

7. Remove the specified key

Boolean result2 = clusterRedisTemplate.delete("setKey");

LIST type related operations

1. Add

//1. Set the value through redisTemplate
clusterRedisTemplate.boundListOps("listKey").leftPush("listLeftValue1");
clusterRedisTemplate.boundListOps("listKey").rightPush("listRightValue2");

//2. Set values through BoundValueOperations
BoundListOperations listKey = clusterRedisTemplate.boundListOps("listKey");
listKey.leftPush("listLeftValue3");
listKey.rightPush("listRightValue4");

//3. Setting values through ValueOperations
ListOperations opsList = clusterRedisTemplate.opsForList();
opsList.leftPush("listKey", "listLeftValue5");
opsList.rightPush("listKey", "listRightValue6");

2. Put the Java List collection into the List type

ArrayList<String> list = new ArrayList<>();
clusterRedisTemplate.boundListOps("listKey").rightPushAll(list);
clusterRedisTemplate.boundListOps("listKey").leftPushAll(list);

3. Set expiration time (set separately)

clusterRedisTemplate.boundValueOps("listKey").expire(1,TimeUnit.MINUTES);
clusterRedisTemplate.expire("listKey",1,TimeUnit.MINUTES);

4. Get all contents of List cache (start index, end index)

List listKey1 = clusterRedisTemplate.boundListOps("listKey").range(0, 10); 

5. Pop an element from left or right

String listKey2 = (String) clusterRedisTemplate.boundListOps("listKey").leftPop();  //Pop up an element from the left
String listKey3 = (String) clusterRedisTemplate.boundListOps("listKey").rightPop(); //Pop up an element from the right

6. Query elements by index

String listKey4 = (String) clusterRedisTemplate.boundListOps("listKey").index(1);

7. Gets the length of the List cache

Long size = clusterRedisTemplate.boundListOps("listKey").size();

8. Modify a piece of data (key, index, value) in the List according to the index

clusterRedisTemplate.boundListOps("listKey").set(3L,"listLeftValue3");

9. Remove N values as value(key, number of removed values)

clusterRedisTemplate.boundListOps("listKey").remove(3L,"value");

Related operations of Zset type

1. Insert an element into the collection and set a score

//1. Set the value through redisTemplate
clusterRedisTemplate.boundZSetOps("zSetKey").add("zSetVaule", 100D);

//2. Set values through BoundValueOperations
BoundZSetOperations zSetKey = clusterRedisTemplate.boundZSetOps("zSetKey");
zSetKey.add("zSetVaule", 100D);

//3. Setting values through ValueOperations
ZSetOperations zSetOps = clusterRedisTemplate.opsForZSet();
zSetOps.add("zSetKey", "zSetVaule", 100D);

2. Insert multiple elements into the collection and set scores

DefaultTypedTuple<String> p1 = new DefaultTypedTuple<>("zSetVaule1", 2.1D);
DefaultTypedTuple<String> p2 = new DefaultTypedTuple<>("zSetVaule2", 3.3D);
clusterRedisTemplate.boundZSetOps("zSetKey").add(new HashSet<>(Arrays.asList(p1,p2)));

3. Print the elements in the specified interval according to the ranking order (from small to large), and - 1 is to print all

Set<String> range = clusterRedisTemplate.boundZSetOps("zSetKey").range(key, 0, -1);

4. Gets the score of the specified element

Double score = clusterRedisTemplate.boundZSetOps("zSetKey").score("zSetVaule");

5. Returns the number of members in the collection

Long size = clusterRedisTemplate.boundZSetOps("zSetKey").size();

6. Returns the number of members in the specified score range in the collection (Double type)

Long count = clusterRedisTemplate.boundZSetOps("zSetKey").count(0D, 2.2D);

7. Returns the ranking (from small to large) of the elements in the collection within the specified score range

Set byScore = clusterRedisTemplate.boundZSetOps("zSetKey").rangeByScore(0D, 2.2D);

8. With offset and number, (key, starting score, maximum score, offset, number)

Set<String> ranking2 = clusterRedisTemplate.opsForZSet().rangeByScore("zSetKey", 0D, 2.2D 1, 3);

9. Returns the ranking of the elements in the collection and the score (from small to large)

Set<TypedTuple<String>> tuples = clusterRedisTemplate.boundZSetOps("zSetKey").rangeWithScores(0L, 3L);
  for (TypedTuple<String> tuple : tuples) {
      System.out.println(tuple.getValue() + " : " + tuple.getScore());
  }

10. Returns the ranking of the specified member

//from small to large
Long startRank = clusterRedisTemplate.boundZSetOps("zSetKey").rank("zSetVaule");
//From big to small
Long endRank = clusterRedisTemplate.boundZSetOps("zSetKey").reverseRank("zSetVaule");

11. Deletes the specified element from the collection

clusterRedisTemplate.boundZSetOps("zSetKey").remove("zSetVaule");

12. Deletes the element (Long type) of the specified index range

clusterRedisTemplate.boundZSetOps("zSetKey").removeRange(0L,3L);

13. Delete elements within the specified score range (Double type)

clusterRedisTemplate.boundZSetOps("zSetKey").removeRangeByScorssse(0D,2.2D);

14. Add points to the specified element (Double type)

Double score = clusterRedisTemplate.boundZSetOps("zSetKey").incrementScore("zSetVaule",1.1D);

 

Keywords: Spring

Added by erfg1 on Tue, 04 Jan 2022 23:46:33 +0200