组件整合之redis(Spring Data Redis 2.X)

快速入门

pom依赖

<!-- spring-data-redis (注意与cluster的版本问题,也注意与spring的版本)-->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>2.1.9.RELEASE</version>
</dependency>
<!--2.9.1有连接泄露的bug-->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.10.2</version>
</dependency>

可能会用到Jackson的相关依赖:

<!--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>

如何配置

单机模式

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 {

    /**
     * 配置连接池
     * @return
     */
    @Bean
    public JedisPoolConfig standalonePoolConfig(){
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        //连接池中最多可空闲链接个数,这里取值20,表示即使没有用数据库链接依然保持20个空闲链接
        poolConfig.setMaxIdle(20);
        //控制一个pool可以分配多少个jedis实例
        poolConfig.setMaxTotal(300);
        //最大等待时间,当没有可用连接时,连接池等待链接被归还的最大时间ms,超过时间就抛出异常
        poolConfig.setMaxWaitMillis(1000);
        //在获取连接的时候检查链接的有效性
        poolConfig.setTestOnCreate(true);
        return poolConfig;
    }

    /**
     * redis单机配置
     * RedisStandaloneConfiguration 单机
     * RedisSentinelConfiguration 主从复制(哨兵模式)
     * RedisClusterConfiguration 集群
     * @return
     */
    @Bean
    public RedisStandaloneConfiguration standaloneConfiguration(){
        RedisStandaloneConfiguration standaloneConfiguration = new RedisStandaloneConfiguration();
        standaloneConfiguration.setHostName("127.0.0.1");
        standaloneConfiguration.setPort(6379);
        standaloneConfiguration.setDatabase(0);
        return standaloneConfiguration;
    }

    /**
     * 配置连接工厂
     * @return
     */
    @Bean
    public JedisConnectionFactory standaloneConnectionFactory(){
        return new JedisConnectionFactory(standaloneConfiguration());
    }

    /**
     * 配置Redis模板
     */
    @Bean
    public RedisTemplate standaloneRedisTemplate(){
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(standaloneConnectionFactory());
        StringRedisSerializer keySerializer = new StringRedisSerializer();
        GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();
        //keySerializer、valueSerializer 配置Redis中的String类型key与value的序列化器
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setValueSerializer(valueSerializer);
        //HashKeySerializer、HashValueSerializer 配置Redis中的Hash类型key与value的序列化器
        redisTemplate.setHashKeySerializer(keySerializer);
        redisTemplate.setHashValueSerializer(valueSerializer);
        return redisTemplate;
    }
}

主从模式(哨兵)

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 {

    /**
     * 配置连接池
     * @return
     */
    @Bean
    public JedisPoolConfig sentinelPoolConfig(){
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        //连接池中最多可空闲链接个数,这里取值20,表示即使没有用数据库链接依然保持20个空闲链接
        poolConfig.setMaxIdle(20);
        //控制一个pool可以分配多少个jedis实例
        poolConfig.setMaxTotal(300);
        //最大等待时间,当没有可用连接时,连接池等待链接被归还的最大时间ms,超过时间就抛出异常
        poolConfig.setMaxWaitMillis(1000);
        //在获取连接的时候检查链接的有效性
        poolConfig.setTestOnCreate(true);
        return poolConfig;
    }

    /**
     * redis哨兵模式
     * RedisStandaloneConfiguration 单机
     * RedisSentinelConfiguration 主从复制(哨兵模式)
     * RedisClusterConfiguration 集群
     * @return
     */
    @Bean
    public RedisSentinelConfiguration sentinelConfiguration(){
        RedisSentinelConfiguration sentinelConfiguration = new RedisSentinelConfiguration();
        //主节点名称
        sentinelConfiguration.setMaster("mymaster");
        //哨兵监听的节点(一主二从)
        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);
        //数据库
        sentinelConfiguration.setDatabase(0);
        return sentinelConfiguration;
    }

    /**
     * 配置连接工厂
     * @return
     */
    @Bean
    public JedisConnectionFactory sentinelConnectionFactory(){
        return new JedisConnectionFactory(sentinelConfiguration());
    }

    /**
     * 配置Redis模板
     */
    @Bean
    public RedisTemplate sentinelRedisTemplate(){
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(sentinelConnectionFactory());
        StringRedisSerializer keySerializer = new StringRedisSerializer();
        GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();
        //keySerializer、valueSerializer 配置Redis中的String类型key与value的序列化器
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setValueSerializer(valueSerializer);
        //HashKeySerializer、HashValueSerializer 配置Redis中的Hash类型key与value的序列化器
        redisTemplate.setHashKeySerializer(keySerializer);
        redisTemplate.setHashValueSerializer(valueSerializer);
        return redisTemplate;
    }
}

集群模式

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 {
    /**
     * 配置连接池
     * @return
     */
    @Bean
    public JedisPoolConfig clusterPoolConfig(){
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        //连接池中最多可空闲链接个数,这里取值20,表示即使没有用数据库链接依然保持20个空闲链接
        poolConfig.setMaxIdle(20);
        //控制一个pool可以分配多少个jedis实例
        poolConfig.setMaxTotal(300);
        //最大等待时间,当没有可用连接时,连接池等待链接被归还的最大时间ms,超过时间就抛出异常
        poolConfig.setMaxWaitMillis(1000);
        //在获取连接的时候检查链接的有效性
        poolConfig.setTestOnCreate(true);
        return poolConfig;
    }

    /**
     * redis集群模式
     * RedisStandaloneConfiguration 单机
     * RedisSentinelConfiguration 主从复制(哨兵模式)
     * RedisClusterConfiguration 集群
     * @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;
    }

    /**
     * 配置连接工厂
     * @return
     */
    @Bean
    public JedisConnectionFactory clusterConnectionFactory(){
        return new JedisConnectionFactory(clusterConfiguration());
    }

    /**
     * 配置Redis模板
     */
    @Bean
    public RedisTemplate clusterRedisTemplate(){
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(clusterConnectionFactory());
        StringRedisSerializer keySerializer = new StringRedisSerializer();
        GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();
        //keySerializer、valueSerializer 配置Redis中的String类型key与value的序列化器
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setValueSerializer(valueSerializer);
        //HashKeySerializer、HashValueSerializer 配置Redis中的Hash类型key与value的序列化器
        redisTemplate.setHashKeySerializer(keySerializer);
        redisTemplate.setHashValueSerializer(valueSerializer);
        return redisTemplate;
    }
}

JedisPoolConfig属性配置

//连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
config.setBlockWhenExhausted(true);
//设置的逐出策略类名, 默认DefaultEvictionPolicy(当连接超过最大空闲时间,或连接数超过最大空闲连接数)
config.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");
//是否启用pool的jmx(Java Management Extensions,即Java管理扩展)管理功能, 默认true
config.setJmxEnabled(true);
//是否启用后进先出, 默认true
config.setLifo(true);
//最大空闲连接数, 默认8个
config.setMaxIdle(10);
//最大连接数, 默认8个
config.setMaxTotal(50);
//获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
config.setMaxWaitMillis(30000);
//资源池中资源最小空闲时间(单位为毫秒),达到此值后空闲资源将被移除  默认1800000毫秒(30分钟)
config.setMinEvictableIdleTimeMillis(60000);
//最小空闲连接数, 默认0
config.setMinIdle(0);
//每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
config.setNumTestsPerEvictionRun(3);
//对象空闲多久后逐出, 当空闲时间>该值 且 空闲连接>最大空闲数 时直接逐出,不再根据MinEvictableIdleTimeMillis判断  (默认逐出策略)
config.setSoftMinEvictableIdleTimeMillis(1800000);
//在获取连接的时候检查有效性, 默认false
config.setTestOnBorrow(false);
//是否开启空闲资源监测, 默认false
config.setTestWhileIdle(true);
//空闲资源的检测周期(单位为毫秒) 如果为负数,则不运行逐出线程, 默认-1
config.setTimeBetweenEvictionRunsMillis(-1);

RedisStandaloneConfiguration 单机配置

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

RedisSentinelConfiguration 主从复制

RedisSentinelConfiguration sentinelConfiguration = new RedisSentinelConfiguration();
//主节点名称
sentinelConfiguration.setMaster("mymaster");
//哨兵监听的节点(一主二从)
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);
//数据库
sentinelConfiguration.setDatabase(0);
sentinelConfiguration.setPassword("123456");

RedisClusterConfiguration 集群配置

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");

JedisConnectionFactory 连接工厂

在spring-data-redis2.0以上版本JedisConnectionFactory中的很多方法都过期了,官方推荐改为构造器中传入配置对象:

  • 单机配置 RedisStandaloneConfiguration
  • 主从复制 RedisSentinelConfiguration
  • 集群 RedisClusterConfiguration  

RedisTemplate Redis模板

(1)手动设置 key与value的序列化方式

序列化器:能够把我们储存的key与value做序列化处理的对象,是一个类似于converter的工具。

可以实现传入的java对象->redis可以识别的数据类型。 如:字符串。

默认的Serializer是StringRedisSerializer。

设定默认的序列化器是字符串序列化器,原因是redis可以存储的数据只有字符串和字节数组。

一般来说,我们代码中操作的数据对象都是java对象。

如果代码中,使用的数据载体就是字符串对象,那么使用Jackson2JsonRedisSerializer来做序列化器是否会有问题?

如果jackson插件的版本不合适,有错误隐患的话,可能将字符串数据转换为json字符串 -> {chars:[], bytes:[]}

使用StringRedisSerializer就没有这个问题,它不处理字符串转换的,认为代码中操作的key和value都是字符串。 

测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={RootConfig.class, WebConfig.class}) //如果是Java Config配置的,指定相关的配置类
@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

通过bound封装指定的key

指定后进行一系列的操作而无须“显式”的再次指定Key,即BoundKeyOperations:

  • BoundValueOperations
  • BoundSetOperations
  • BoundListOperations
  • BoundSetOperations
  • BoundHashOperations
//1、通过redisTemplate设置值
clusterRedisTemplate.boundValueOps("StringKey").set("StringValue");
clusterRedisTemplate.boundValueOps("StringKey").set("StringValue", 1, TimeUnit.MINUTES);
//2、通过BoundValueOperations设置值
BoundValueOperations stringKey = clusterRedisTemplate.boundValueOps("StringKey");
stringKey.set("StringValue");
stringKey.set("StringValue", 1, TimeUnit.MINUTES);
//3、通过ValueOperations设置值
ValueOperations ops = clusterRedisTemplate.opsForValue();
ops.set("StringKey", "StringValue");
ops.set("StringValue", "StringValue", 1, TimeUnit.MINUTES);
//1、通过redisTemplate获取值
String str1 = (String) clusterRedisTemplate.boundValueOps("StringKey").get();
//2、通过BoundValueOperations获取值
BoundValueOperations stringKey = clusterRedisTemplate.boundValueOps("StringKey");
String str2 = (String) stringKey.get();
//3、通过ValueOperations获取值
ValueOperations ops = clusterRedisTemplate.opsForValue();
String str3 = (String) ops.get("StringKey");

基本API

//删除key
clusterRedisTemplate.delete(keys);
//指定key的失效时间
clusterRedisTemplate.expire(key,time,TimeUnit.MINUTES);
//根据key获取过期时间
Long expire = clusterRedisTemplate.getExpire(key);
//判断key是否存在
clusterRedisTemplate.hasKey(key);
//顺序递增
clusterRedisTemplate.boundValueOps("StringKey").increment(3L);
//顺序递减
clusterRedisTemplate.boundValueOps("StringKey").increment(-3L);

Hash类型相关操作

1、设置值

//1、通过redisTemplate设置值
clusterRedisTemplate.boundHashOps("HashKey").put("SmallKey", "HashVaue");
//2、通过BoundValueOperations设置值
BoundHashOperations hashKey = clusterRedisTemplate.boundHashOps("HashKey");
hashKey.put("SmallKey", "HashVaue");
//3、通过ValueOperations设置值
HashOperations hashOps = clusterRedisTemplate.opsForHash();
hashOps.put("HashKey", "SmallKey", "HashVaue");

2、设置过期时间(单独设置)

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

3、添加一个Map集合

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

4、提取Hash中的小key

//1、通过redisTemplate获取值
Set keys1 = clusterRedisTemplate.boundHashOps("HashKey").keys();
//2、通过BoundValueOperations获取值
BoundHashOperations hashKey = clusterRedisTemplate.boundHashOps("HashKey");
Set keys2 = hashKey.keys();
//3、通过ValueOperations获取值
HashOperations hashOps = clusterRedisTemplate.opsForHash();
Set keys3 = hashOps.keys("HashKey");

5、提取所有的value值

//1、通过redisTemplate获取值
List values1 = clusterRedisTemplate.boundHashOps("HashKey").values();
//2、通过BoundValueOperations获取值
BoundHashOperations hashKey = clusterRedisTemplate.boundHashOps("HashKey");
List values2 = hashKey.values();
//3、通过ValueOperations获取值
HashOperations hashOps = clusterRedisTemplate.opsForHash();
List values3 = hashOps.values("HashKey");

6、根据Hash的key提取value值

//1、通过redisTemplate获取
String value1 = (String) clusterRedisTemplate.boundHashOps("HashKey").get("SmallKey");
//2、通过BoundValueOperations获取值
BoundHashOperations hashKey = clusterRedisTemplate.boundHashOps("HashKey");
String value2 = (String) hashKey.get("SmallKey");
//3、通过ValueOperations获取值
HashOperations hashOps = clusterRedisTemplate.opsForHash();
String value3 = (String) hashOps.get("HashKey", "SmallKey");

7、获取所有的键值对集合

//1、通过redisTemplate获取
Map entries = clusterRedisTemplate.boundHashOps("HashKey").entries();
//2、通过BoundValueOperations获取值
BoundHashOperations hashKey = clusterRedisTemplate.boundHashOps("HashKey");
Map entries1 = hashKey.entries();
//3、通过ValueOperations获取值
HashOperations hashOps = clusterRedisTemplate.opsForHash();
Map entries2 = hashOps.entries("HashKey");

8、删除

//删除小key
clusterRedisTemplate.boundHashOps("HashKey").delete("SmallKey");
//删除大key
clusterRedisTemplate.delete("HashKey");

9、判断Hash中是否含有该值

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

Set类型相关操作

1、添加

//1、通过redisTemplate设置值
clusterRedisTemplate.boundSetOps("setKey").add("setValue1", "setValue2", "setValue3");

//2、通过BoundValueOperations设置值
BoundSetOperations setKey = clusterRedisTemplate.boundSetOps("setKey");
setKey.add("setValue1", "setValue2", "setValue3");

//3、通过ValueOperations设置值
SetOperations setOps = clusterRedisTemplate.opsForSet();
setOps.add("setKey", "SetValue1", "setValue2", "setValue3");

2、设置过期时间(单独设置)

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

3、根据key获取Set中的所有值

//1、通过redisTemplate获取值
Set set1 = clusterRedisTemplate.boundSetOps("setKey").members();

//2、通过BoundValueOperations获取值
BoundSetOperations setKey = clusterRedisTemplate.boundSetOps("setKey");
Set set2 = setKey.members();

//3、通过ValueOperations获取值
SetOperations setOps = clusterRedisTemplate.opsForSet();
Set set3 = setOps.members("setKey");

4、查询value是否已存在

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

5、获取Set的长度

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

6、移除指定的元素

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

7、移除指定的key

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

LIST类型相关操作

1、添加

//1、通过redisTemplate设置值
clusterRedisTemplate.boundListOps("listKey").leftPush("listLeftValue1");
clusterRedisTemplate.boundListOps("listKey").rightPush("listRightValue2");

//2、通过BoundValueOperations设置值
BoundListOperations listKey = clusterRedisTemplate.boundListOps("listKey");
listKey.leftPush("listLeftValue3");
listKey.rightPush("listRightValue4");

//3、通过ValueOperations设置值
ListOperations opsList = clusterRedisTemplate.opsForList();
opsList.leftPush("listKey", "listLeftValue5");
opsList.rightPush("listKey", "listRightValue6");

2、将Java的List集合放入List类型

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

3、设置过期时间(单独设置)

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

4、获取List缓存全部内容(起始索引,结束索引)

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

5、从左或从右弹出一个元素

String listKey2 = (String) clusterRedisTemplate.boundListOps("listKey").leftPop();  //从左侧弹出一个元素
String listKey3 = (String) clusterRedisTemplate.boundListOps("listKey").rightPop(); //从右侧弹出一个元素

6、根据索引查询元素

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

7、获取List缓存的长度

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

8、根据索引修改List中的某条数据(key,索引,值)

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

9、移除N个值为value(key,移除个数,值)

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

Zset类型的相关操作

1、向集合中插入元素,并设置分数

//1、通过redisTemplate设置值
clusterRedisTemplate.boundZSetOps("zSetKey").add("zSetVaule", 100D);

//2、通过BoundValueOperations设置值
BoundZSetOperations zSetKey = clusterRedisTemplate.boundZSetOps("zSetKey");
zSetKey.add("zSetVaule", 100D);

//3、通过ValueOperations设置值
ZSetOperations zSetOps = clusterRedisTemplate.opsForZSet();
zSetOps.add("zSetKey", "zSetVaule", 100D);

2、向集合中插入多个元素,并设置分数

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、按照排名先后(从小到大)打印指定区间内的元素, -1为打印全部

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

4、获得指定元素的分数

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

5、返回集合内的成员个数

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

6、返回集合内指定分数范围的成员个数(Double类型)

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

7、返回集合内元素在指定分数范围内的排名(从小到大)

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

8、带偏移量和个数,(key,起始分数,最大分数,偏移量,个数)

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

9、返回集合内元素的排名,以及分数(从小到大)

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

10、返回指定成员的排名 

//从小到大
Long startRank = clusterRedisTemplate.boundZSetOps("zSetKey").rank("zSetVaule");
//从大到小
Long endRank = clusterRedisTemplate.boundZSetOps("zSetKey").reverseRank("zSetVaule");

11、从集合中删除指定元素

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

12、删除指定索引范围的元素(Long类型)

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

13、删除指定分数范围内的元素(Double类型)

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

14、为指定元素加分(Double类型)

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

 

posted @ 2022-01-04 08:33  残城碎梦  阅读(95)  评论(0编辑  收藏  举报