详解SpringBoot使用RedisTemplate操作Redis的5种数据类型

2022-07-16,,,,

spring 封装了 redistemplate 来操作 redis,它支持所有的 redis 原生的 api。在 redistemplate 中定义了对5种数据结构的操作方法。

  • opsforvalue():操作字符串。
  • opsforlist():操作列表。
  • opsforhash():操作哈希。
  • opsforset():操作集合。
  • opsforzset():操作有序集合。

下面通过实例来理解和应用这些方法。这里需要特别注意的是,运行上述方法后要对数据进行清空操作,否则多次运行会导致数据重复操作。

(1)使用maven添加依赖文件

在pom.xml配置信息文件中,添加redis依赖:

我的springboot版本:

<parent>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-parent</artifactid>
    <version>2.3.4.release</version>
    <relativepath/> <!-- lookup parent from repository -->
</parent>

添加redis依赖:

<!-- redis启动器 -->
<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-data-redis</artifactid>
    <version>2.3.3.release</version>
</dependency>

(2)redis的配置

在 application.yml 配置文件中配置redis信息:

#spring配置
spring:
  #缓存管理器
  cache:
    type: redis
  #redis配置
  redis:
    database: 0 #redis数据库索引(默认为0)
    host: 127.0.0.1 #redis服务器地址
    port: 6379 #redis服务器连接端口
    password:  #redis服务器连接密码(默认为空)
    jedis:
      pool:
        max-active: 8 #连接池最大连接数(使用负值表示没有限制)
        max-wait: -1s #连接池最大阻塞等待时间(使用负值表示没有限制)
        max-idle: 8  #连接池中的最大空闲连接
        min-idle: 0 #连接池中的最小空闲连接
    lettuce:
      shutdown-timeout: 100ms #关闭超时时间,默认值100ms

(3)redis配置类(config层)

创建com.pjb.config包中,并创建redisconfig类(redis配置类),并继承cachingconfigurersupport类。

package com.pjb.config;
 
import com.fasterxml.jackson.annotation.jsonautodetect;
import com.fasterxml.jackson.annotation.propertyaccessor;
import com.fasterxml.jackson.databind.objectmapper;
import org.springframework.cache.cachemanager;
import org.springframework.cache.annotation.cachingconfigurersupport;
import org.springframework.cache.interceptor.keygenerator;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.data.redis.cache.rediscachemanager;
import org.springframework.data.redis.connection.redisconnectionfactory;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.data.redis.core.stringredistemplate;
import org.springframework.data.redis.serializer.jackson2jsonredisserializer;
 
import java.lang.reflect.method;
 
/**
 * redis配置类
 * @author pan_junbiao
 **/
@configuration
public class redisconfig extends cachingconfigurersupport
{
    /**
     * 缓存对象集合中,缓存是以key-value形式保存的,
     * 当不指定缓存的key时,springboot会使用keygenerator生成key。
     */
    @bean
    public keygenerator keygenerator()
    {
        return new keygenerator()
        {
            @override
            public object generate(object target, method method, object... params) {
                stringbuilder sb = new stringbuilder();
                //类名+方法名
                sb.append(target.getclass().getname());
                sb.append(method.getname());
                for (object obj : params) {
                    sb.append(obj.tostring());
                }
                return sb.tostring();
            }
        };
    }
 
    /**
     * 缓存管理器
     */
    @suppresswarnings("rawtypes")
    @bean
    public cachemanager cachemanager(redisconnectionfactory connectionfactory)
    {
        rediscachemanager cachemanager = rediscachemanager.create(connectionfactory);
        //设置缓存过期时间
 
        return cachemanager;
    }
 
    /**
     * 实例化redistemplate对象
     */
    @bean
    public redistemplate<string, string> redistemplate(redisconnectionfactory factory)
    {
        stringredistemplate template = new stringredistemplate(factory);
        jackson2jsonredisserializer jackson2jsonredisserializer = new jackson2jsonredisserializer(object.class);
        objectmapper om = new objectmapper();
        om.setvisibility(propertyaccessor.all, jsonautodetect.visibility.any);
        om.enabledefaulttyping(objectmapper.defaulttyping.non_final);
        jackson2jsonredisserializer.setobjectmapper(om);
        template.setvalueserializer(jackson2jsonredisserializer);
        template.afterpropertiesset();
        return template;
    }
}

1、字符串(string)

字符串(string)是 redis 最基本的数据类型。string 的一个“key”对应一个“value”,即 key-value 键值对。string 是二进制安全的,可以存储任何数据(比如图片或序列化的对象)。值最大能存储512mb的数据。一般用于一些复杂的计数功能的缓存。redistemplate 提供以下操作 string 的方法。

1.1 void set(k key, v value);v get(object key)

具体用法见以下代码:

/**
 * redis操作字符串(string)
 * @author pan_junbiao
 **/
@springboottest
public class stringtest
{
    @autowired
    private redistemplate redistemplate;
    
    @test
    public void string1()
    {
        redistemplate.opsforvalue().set("username","pan_junbiao的博客");
        redistemplate.opsforvalue().set("blogurl","https://blog.csdn.net/pan_junbiao");
        redistemplate.opsforvalue().set("blogremark","您好,欢迎访问 pan_junbiao的博客");
        system.out.println("用户名称:" + redistemplate.opsforvalue().get("username"));
        system.out.println("博客地址:" + redistemplate.opsforvalue().get("blogurl"));
        system.out.println("博客信息:" + redistemplate.opsforvalue().get("blogremark"));
    }
}

执行结果:

1.2 void set(k key, v value, long timeout, timeunit unit)

以下代码设置3s失效。3s之内查询有结果,3s之后查询返回为null。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void string2()
{
    //设置的是3s失效,3s之内查询有结果,3s之后返回null
    redistemplate.opsforvalue().set("blogremark","您好,欢迎访问 pan_junbiao的博客",3, timeunit.seconds);
    try
    {
        object s1 = redistemplate.opsforvalue().get("blogremark");
        system.out.println("博客信息:" + s1);
        thread.currentthread().sleep(2000);
 
        object s2 = redistemplate.opsforvalue().get("blogremark");
        system.out.println("博客信息:" + s2);
        thread.currentthread().sleep(5000);
 
        object s3 = redistemplate.opsforvalue().get("blogremark");
        system.out.println("博客信息:" + s3);
    }
    catch (interruptedexception ie)
    {
        ie.printstacktrace();
    }
}

执行结果:

1.3 v getandset(k key, v value)

设置键的字符串,并返回其旧值。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void string3()
{
    //设置键的字符串并返回其旧值
    redistemplate.opsforvalue().set("blogremark","pan_junbiao的博客");
    object oldvaule = redistemplate.opsforvalue().getandset("blogremark","您好,欢迎访问 pan_junbiao的博客");
    object newvaule = redistemplate.opsforvalue().get("blogremark");
    system.out.println("旧值:" + oldvaule);
    system.out.println("新值:" + newvaule);
}

执行结果:

1.4 integer append(k key, v value)

如果key已经存在,并且是一个字符串,则该命令将该值追加到字符串的末尾。如果key不存在,则它将被创建并设置为空字符串,因此 append 在这种特殊情况下类似于 set。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void string4()
{
    //设置value的序列化规则,否则会报错
    redistemplate.setvalueserializer(new stringredisserializer());
 
    redistemplate.opsforvalue().append("blogremark","您好,欢迎访问 ");
    system.out.println(redistemplate.opsforvalue().get("blogremark"));
    redistemplate.opsforvalue().append("blogremark","pan_junbiao的博客");
    system.out.println(redistemplate.opsforvalue().get("blogremark"));
}

执行结果:

注意:这里一定要注意反序列化配置,否则会报错。

1.5 long size(k key)

返回key所对应的value值的长度,见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void string5()
{
    redistemplate.opsforvalue().set("username","pan_junbiao的博客");
    system.out.println("value值:" + redistemplate.opsforvalue().get("username"));
    system.out.println("value值的长度:" + redistemplate.opsforvalue().size("username"));
}

执行结果:

2、列表(list)

redis列表是简单的字符串列表,按照插入顺序排序。可以添加一个元素到列表的头部(左边)或尾部(右边)。

使用list数据结果,可以做简单的消息队列的功能。还可以利用 irange 命令,做基于reids的分页功能,性能极佳。

2.1 long leftpushall(k key, v... values);long rightpushall(k key, v... values)

leftpushall方法:表示把一个数组插入列表中。

rightpushall方法:表示向列表的最右边批量添加元素。具体用法见以下代码:

/**
 * redis操作列表(list)
 * @author pan_junbiao
 **/
@springboottest
public class listtest
{
    @autowired
    private redistemplate redistemplate;
 
    @test
    public void list1()
    {
        string[] user1 = new string[]{"1","pan_junbiao的博客","您好,欢迎访问 pan_junbiao的博客"};
        string[] user2 = new string[]{"2","pan_junbiao的博客","https://blog.csdn.net/pan_junbiao"};
        string[] user3 = new string[]{"3","pan_junbiao的博客","您好,欢迎访问 pan_junbiao的博客"};
 
        redistemplate.opsforlist().rightpushall("user1",user1);
        redistemplate.opsforlist().rightpushall("user2",user2);
        redistemplate.opsforlist().rightpushall("user3",user3);
 
        system.out.println(redistemplate.opsforlist().range("user1",0,-1));
        system.out.println(redistemplate.opsforlist().range("user2",0,-1));
        system.out.println(redistemplate.opsforlist().range("user3",0,-1));
    }
}

执行结果:

2.2 long leftpush(k key, v value);long rightpush(k key, v value)

leftpush方法:将所有指定的值插入在键的列表的头部。如果键不存在,则在执行推送操作之前将其创建为空列表(从左边插入)。

rightpush方法:将所有指定的值插入在键的列表的尾部。如果键不存在,则在执行推送操作之前将其创建为空列表(从右边插入)。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void list2()
{
    redistemplate.opsforlist().rightpush("userinfo",1);
    redistemplate.opsforlist().rightpush("userinfo","pan_junbiao的博客");
    redistemplate.opsforlist().rightpush("userinfo","https://blog.csdn.net/pan_junbiao");
    redistemplate.opsforlist().rightpush("userinfo","您好,欢迎访问 pan_junbiao的博客");
 
    system.out.println("用户编号:" + redistemplate.opsforlist().index("userinfo",0));
    system.out.println("用户名称:" + redistemplate.opsforlist().index("userinfo",1));
    system.out.println("博客地址:" + redistemplate.opsforlist().index("userinfo",2));
    system.out.println("博客信息:" + redistemplate.opsforlist().index("userinfo",3));
}

执行结果:

2.3 long size(k key)

返回存储在键中的列表的长度。如果键不存在,则将其解释为空列表,并返回0。如果key存在的值不是列表,则返回错误。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void list3()
{
    string[] user = new string[]{"1","pan_junbiao的博客","您好,欢迎访问 pan_junbiao的博客"};
    redistemplate.opsforlist().leftpushall("user",user);
    system.out.println("列表的长度:" + redistemplate.opsforlist().size("user"));
}

执行结果:

2.4 void set(k key, long index, v value)

在列表中 index 的位置设置 value。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void list4()
{
    string[] user = new string[]{"1","pan_junbiao的博客","https://blog.csdn.net/pan_junbiao"};
    redistemplate.opsforlist().rightpushall("user",user);
    system.out.println(redistemplate.opsforlist().range("user",0,-1));
 
    redistemplate.opsforlist().set("user",2,"您好,欢迎访问 pan_junbiao的博客");
    system.out.println(redistemplate.opsforlist().range("user",0,-1));
}

执行结果:

2.5 v index(k key, long index)

根据下标获取列表中的值(下标从0开始)。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void list2()
{
    redistemplate.opsforlist().rightpush("userinfo",1);
    redistemplate.opsforlist().rightpush("userinfo","pan_junbiao的博客");
    redistemplate.opsforlist().rightpush("userinfo","https://blog.csdn.net/pan_junbiao");
    redistemplate.opsforlist().rightpush("userinfo","您好,欢迎访问 pan_junbiao的博客");
 
    system.out.println("用户编号:" + redistemplate.opsforlist().index("userinfo",0));
    system.out.println("用户名称:" + redistemplate.opsforlist().index("userinfo",1));
    system.out.println("博客地址:" + redistemplate.opsforlist().index("userinfo",2));
    system.out.println("博客信息:" + redistemplate.opsforlist().index("userinfo",3));
}

执行结果:

2.6 long remove(k key, long count, object value)

从存储在键中的列表,删除给定“count”值的元素的第1个计数事件。其中,参数count的含义如下:

  • count=0:删除等于value的所有元素。
  • count>0:删除等于从头到尾移动的值的元素。
  • count<0:删除等于从尾到头移动的值的元素。

以下代码用于删除列表中第一次出现的值:

@autowired
private redistemplate redistemplate;
 
@test
public void list5()
{
    string[] user = new string[]{"1","pan_junbiao的博客","您好,欢迎访问 pan_junbiao的博客"};
    redistemplate.opsforlist().rightpushall("user",user);
    system.out.println(redistemplate.opsforlist().range("user",0,-1));
 
    //将删除列表中第一次出现的pan_junbiao的博客
    redistemplate.opsforlist().remove("user",1,"pan_junbiao的博客");
    system.out.println(redistemplate.opsforlist().range("user",0,-1));
}

执行结果:

2.7 v leftpop(k key);v rightpop(k key)

leftpop方法:弹出最左边的元素,弹出之后该值在列表中将不复存在。

rightpop方法:弹出最右边的元素,弹出之后该值在列表中将不复存在。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void list6()
{
    string[] user = new string[]{"1","pan_junbiao的博客","您好,欢迎访问 pan_junbiao的博客"};
    redistemplate.opsforlist().rightpushall("user",user);
    system.out.println(redistemplate.opsforlist().range("user",0,-1));
    //弹出最右边的元素,弹出之后该值在列表中将不复存在
    system.out.println(redistemplate.opsforlist().rightpop("user"));
    system.out.println(redistemplate.opsforlist().range("user",0,-1));
}

执行结果:

3、哈希(hash)

redis 中的 hash(哈希)是一个 string 类型的 field 和 value 的映射表,hash 特别适合用于存储对象。value 中存放的是结构化的对象。利用这样数据结果,可以方便地操作其中的某个字段。比如在“单点登录”时,可以用这种数据结构存储用户信息。以 cookieid 作为 key,设置30分钟为缓存过期时间,能很好地模拟出类似 session 的效果。

3.1 void putall(h key, map<? extends hk, ? extends hv> m);map<hk, hv> entries(h key)

putall方法:用 m 中提供的多个散列字段设置到 key 对应的散列表中。

entries方法:根据密钥获取整个散列存储。具体用法见以下代码:

/**
 * redis操作哈希(hash)
 * @author pan_junbiao
 **/
@springboottest
public class hashtest
{
    @autowired
    private redistemplate redistemplate;
 
    @test
    public void hash1()
    {
        map<string,object> usermap = new hashmap<>();
        usermap.put("username","pan_junbiao的博客");
        usermap.put("blogremark","您好,欢迎访问 pan_junbiao的博客");
        redistemplate.opsforhash().putall("userhash",usermap);
        system.out.println(redistemplate.opsforhash().entries("userhash"));
    }
}

执行结果:

3.2 void put(h key, hk hashkey, hv value);hv get(h key, object hashkey)

put方法:设置 hashkey 的值。

get方法:从键中的散列获取给定 hashkey 的值。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void hash2()
{
    redistemplate.opsforhash().put("userhash","username","pan_junbiao的博客");
    redistemplate.opsforhash().put("userhash","blogurl","https://blog.csdn.net/pan_junbiao");
    redistemplate.opsforhash().put("userhash","blogremark","您好,欢迎访问 pan_junbiao的博客");
    system.out.println("用户名称:" + redistemplate.opsforhash().get("userhash","username"));
    system.out.println("博客地址:" + redistemplate.opsforhash().get("userhash","blogurl"));
    system.out.println("博客信息:" + redistemplate.opsforhash().get("userhash","blogremark"));
}

执行结果:

3.3 list<hv> values(h key);set<hk> keys(h key)

values方法:根据密钥获取整个散列存储的值。

keys方法:根据密钥获取整个散列存储的键。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void hash3()
{
    redistemplate.opsforhash().put("userhash","username","pan_junbiao的博客");
    redistemplate.opsforhash().put("userhash","blogremark","您好,欢迎访问 pan_junbiao的博客");
    system.out.println("散列存储的值:" + redistemplate.opsforhash().values("userhash"));
    system.out.println("散列存储的键:" + redistemplate.opsforhash().keys("userhash"));
}

执行结果:

3.4 boolean haskey(h key, object hashkey);long size(h key)

haskey方法:确定 hashkey 是否存在。

size方法:获取 key 所对应的散列表的大小个数。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void hash4()
{
    redistemplate.opsforhash().put("userhash","username","pan_junbiao的博客");
    redistemplate.opsforhash().put("userhash","blogurl","https://blog.csdn.net/pan_junbiao");
    redistemplate.opsforhash().put("userhash","blogremark","您好,欢迎访问 pan_junbiao的博客");
    system.out.println(redistemplate.opsforhash().haskey("userhash","username"));
    system.out.println(redistemplate.opsforhash().haskey("userhash","age"));
    system.out.println(redistemplate.opsforhash().size("userhash"));
}

执行结果:

3.5 long delete(h key, object... hashkeys)

删除给定的 hashkeys。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void hash5()
{
    redistemplate.opsforhash().put("userhash","username","pan_junbiao的博客");
    redistemplate.opsforhash().put("userhash","blogremark","您好,欢迎访问 pan_junbiao的博客");
    system.out.println(redistemplate.opsforhash().delete("userhash","blogremark"));
    system.out.println(redistemplate.opsforhash().entries("userhash"));
}

执行结果:

4、集合(set)

set 是存放不重复值的集合。利用 set 可以做全局去重复的功能。还可以进行交集、并集、差集等操作,也可用来实现计算共同喜好、全部的喜好、自己独有的喜好等功能。

redis 的 set 是 string 类型的无序集合,通过散列表实现。

4.1 long add(k key, v... values);set<v> members(k key)

add方法:在无序集合中添加元素,返回添加个数;如果存在重复的则不进行添加。

members方法:返回集合中的所有成员。具体用法见以下代码:

/**
 * redis操作集合(set)
 * @author pan_junbiao
 **/
@springboottest
public class settest
{
    @autowired
    private redistemplate redistemplate;
 
    @test
    public void set1()
    {
        string[] citys = new string[]{"北京","上海","广州","深圳"};
        system.out.println(redistemplate.opsforset().add("cityset",citys));
        system.out.println(redistemplate.opsforset().add("cityset","香港","澳门","台湾"));
        //返回集合中的所有元素
        system.out.println(redistemplate.opsforset().members("cityset"));
    }
}

执行结果:

4.2 long remove(k key, object... values)

移除集合中一个或多个成员。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void set2()
{
    string[] citys = new string[]{"北京","上海","广州","深圳"};
    system.out.println(redistemplate.opsforset().add("cityset",citys));
    system.out.println(redistemplate.opsforset().remove("cityset",citys));
}

执行结果:

4.3 v pop(k key)

移除并返回集合中的一个随机元素。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void set3()
{
    string[] citys = new string[]{"北京","上海","广州","深圳"};
    system.out.println(redistemplate.opsforset().add("cityset",citys));
    system.out.println(redistemplate.opsforset().pop("cityset"));
    system.out.println(redistemplate.opsforset().members("cityset"));
}

执行结果:

4.4 boolean move(k key, v value, k destkey)

将 member 元素移动。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void set4()
{
    string[] citys = new string[]{"北京","上海","广州","深圳"};
    system.out.println(redistemplate.opsforset().add("cityset",citys));
    system.out.println(redistemplate.opsforset().move("cityset","深圳","cityset2"));
    system.out.println(redistemplate.opsforset().members("cityset"));
    system.out.println(redistemplate.opsforset().members("cityset2"));
}

执行结果:

4.5 cursor<v> scan(k key, scanoptions options)

用于遍历 set。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void set5()
{
    string[] citys = new string[]{"北京","上海","广州","深圳"};
    system.out.println(redistemplate.opsforset().add("cityset",citys));
    cursor<object> cursor = redistemplate.opsforset().scan("cityset", scanoptions.none);
    while(cursor.hasnext())
    {
        system.out.println(cursor.next());
    }
}

执行结果:

4.6 交集、并集、差集

  • set<v> intersect(k key1, k key2)方法、long intersectandstore(k key1, k key2, k destkey)方法:交集。
  • set<v> union(k key1, k key2)方法、long unionandstore(k key1, k key2, k destkey)方法:并集。
  • set<v> difference(k key1, k key2)方法、long differenceandstore(k key1, k key2, k destkey)方法:差集。

具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void set6()
{
    string[] city1 = new string[]{"北京", "上海", "广州", "深圳", "昆明"};
    string[] city2 = new string[]{"北京", "深圳", "昆明", "成都"};
    system.out.println(redistemplate.opsforset().add("cityset1", city1));
    system.out.println(redistemplate.opsforset().add("cityset2", city2));
 
    //返回集合中的所有元素
    system.out.println("城市集合1:" + redistemplate.opsforset().members("cityset1"));
    system.out.println("城市集合2:" + redistemplate.opsforset().members("cityset2"));
 
    //求交集、并集、差集(方式一)
    system.out.println("求交集、并集、差集(方式一):");
    system.out.println("交集:" + redistemplate.opsforset().intersect("cityset1","cityset2"));
    system.out.println("并集:" + redistemplate.opsforset().union("cityset1","cityset2"));
    system.out.println("差集:" + redistemplate.opsforset().difference("cityset1","cityset2"));
 
    //求交集、并集、差集(方式二)
    redistemplate.opsforset().intersectandstore("cityset1","cityset2", "intersectcity");
    redistemplate.opsforset().unionandstore("cityset1","cityset2", "unioncity");
    redistemplate.opsforset().differenceandstore("cityset1","cityset2", "differencecity");
    system.out.println("求交集、并集、差集(方式二):");
    system.out.println("交集:" + redistemplate.opsforset().members("intersectcity"));
    system.out.println("并集:" + redistemplate.opsforset().members("unioncity"));
    system.out.println("差集:" + redistemplate.opsforset().members("differencecity"));
}

执行结果:

5、有序集合(sorted set)

zset(sorted set 有序集合)也是 string 类型元素的集合,且不允许重复的成员。每个元素都会关联一个 double 类型的分数。可以通过分数将该集合中的成员从小到大进行排序。

zset 的成员是唯一的,但权重参数分数(score)却可以重复。集合中的元素能够按 score 进行排列。它可以用来做排行榜应用、取top/n、延时任务、范围查找等。

5.1 long add(k key, set<zsetoperations.typedtuple<v>> tuples)

增加一个有序集合。具体用法见以下代码:

import org.junit.jupiter.api.aftereach;
import org.junit.jupiter.api.beforeeach;
import org.junit.jupiter.api.test;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.test.context.springboottest;
import org.springframework.data.redis.core.defaulttypedtuple;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.data.redis.core.zsetoperations;
 
import java.util.hashset;
import java.util.set;
/**
 * redis操作有序集合(sorted set)
 * @author pan_junbiao
 **/
@springboottest
public class sortedsettest
{
    @autowired
    private redistemplate redistemplate;
 
    @test
    public void zset1() 
    {
        zsetoperations.typedtuple<string> objecttypedtuple1 = new defaulttypedtuple<>("pan_junbiao的博客_01",9.6);
        zsetoperations.typedtuple<string> objecttypedtuple2 = new defaulttypedtuple<>("pan_junbiao的博客_02",1.5);
        zsetoperations.typedtuple<string> objecttypedtuple3 = new defaulttypedtuple<>("pan_junbiao的博客_03",7.4);
 
        set<zsetoperations.typedtuple<string>> typles = new hashset<zsetoperations.typedtuple<string>>();
        typles.add(objecttypedtuple1);
        typles.add(objecttypedtuple2);
        typles.add(objecttypedtuple3);
 
        system.out.println(redistemplate.opsforzset().add("typles",typles));
        system.out.println(redistemplate.opsforzset().range("typles",0,-1));
    }
}

执行结果:

5.2 boolean add(k key, v value, double score)

新增一个有序集合,存在的话为false,不存在的话为true。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void zset2()
{
    system.out.println(redistemplate.opsforzset().add("zset2", "pan_junbiao的博客_01", 9.6));
    system.out.println(redistemplate.opsforzset().add("zset2", "pan_junbiao的博客_01", 9.6));
}

执行结果:

5.3 long remove(k key, object... values)

从有序集合中移除一个或者多个元素。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void zset3()
{
    system.out.println(redistemplate.opsforzset().add("zset3", "pan_junbiao的博客_01", 1.0));
    system.out.println(redistemplate.opsforzset().add("zset3", "pan_junbiao的博客_02", 1.0));
    system.out.println(redistemplate.opsforzset().range("zset3", 0, -1));
    system.out.println(redistemplate.opsforzset().remove("zset3", "pan_junbiao的博客_02"));
    system.out.println(redistemplate.opsforzset().range("zset3", 0, -1));
}

执行结果:

5.4 long rank(k key, object value)

返回有序集中指定成员的排名,其中有序集成员按分数值递增(从小到大)顺序排列。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void zset4()
{
    system.out.println(redistemplate.opsforzset().add("zset4", "pan_junbiao的博客_01",9.6));
    system.out.println(redistemplate.opsforzset().add("zset4", "pan_junbiao的博客_02",1.5));
    system.out.println(redistemplate.opsforzset().add("zset4", "pan_junbiao的博客_03",7.4));
    system.out.println(redistemplate.opsforzset().range("zset4", 0, -1));
    system.out.println(redistemplate.opsforzset().rank("zset4", "pan_junbiao的博客_02"));
}

执行结果:

注意:结果中的0表示第一(最小)。

5.5 set<v> range(k key, long start, long end);set<v> rangebyscore(k key, double score1, double score2)

range方法:通过索引区间返回有序集合成指定区间内的成员,其中有序集成员按分数值递增(从小到大)顺序排列。

rangebyscore方法:通过分数区间返回有序集合成指定区间内的成员,其中有序集成员按分数值递增(从小到大)顺序排列。

具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void zset5()
{
    zsetoperations.typedtuple<string> objecttypedtuple1 = new defaulttypedtuple<>("pan_junbiao的博客_01",9.6);
    zsetoperations.typedtuple<string> objecttypedtuple2 = new defaulttypedtuple<>("pan_junbiao的博客_02",1.5);
    zsetoperations.typedtuple<string> objecttypedtuple3 = new defaulttypedtuple<>("pan_junbiao的博客_03",7.4);
 
    set<zsetoperations.typedtuple<string>> typles = new hashset<zsetoperations.typedtuple<string>>();
    typles.add(objecttypedtuple1);
    typles.add(objecttypedtuple2);
    typles.add(objecttypedtuple3);
 
    system.out.println(redistemplate.opsforzset().add("zset5",typles));
    system.out.println(redistemplate.opsforzset().range("zset5",0,-1));
    system.out.println(redistemplate.opsforzset().rangebyscore("zset5", 0, 8));
}

执行结果:

5.6 long count(k key, double score1, double score2);long size(k key)

count方法:通过分数返回有序集合指定区间内的成员个数。

size方法:获取有序集合的成员数。

具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void zset6()
{
    zsetoperations.typedtuple<string> objecttypedtuple1 = new defaulttypedtuple<>("pan_junbiao的博客_01",9.6);
    zsetoperations.typedtuple<string> objecttypedtuple2 = new defaulttypedtuple<>("pan_junbiao的博客_02",1.5);
    zsetoperations.typedtuple<string> objecttypedtuple3 = new defaulttypedtuple<>("pan_junbiao的博客_03",7.4);
 
    set<zsetoperations.typedtuple<string>> typles = new hashset<zsetoperations.typedtuple<string>>();
    typles.add(objecttypedtuple1);
    typles.add(objecttypedtuple2);
    typles.add(objecttypedtuple3);
 
    redistemplate.opsforzset().add("zset6", typles);
    system.out.println("分数在0至8区间内的成员个数:" + redistemplate.opsforzset().count("zset6", 0, 8));
    system.out.println("有序集合的成员数:" + redistemplate.opsforzset().size("zset6"));
}

执行结果:

5.7 double score(k key, object o)

获取指定成员的score值。具体用法见以下代码:

@test
public void zset7()
{
    redistemplate.opsforzset().add("zset7", "pan_junbiao的博客_01", 9.6);
    redistemplate.opsforzset().add("zset7", "pan_junbiao的博客_02", 1.5);
    redistemplate.opsforzset().add("zset7", "pan_junbiao的博客_03", 7.4);
 
    system.out.println("pan_junbiao的博客_01的分数:" + redistemplate.opsforzset().score("zset7", "pan_junbiao的博客_01"));
    system.out.println("pan_junbiao的博客_02的分数:" + redistemplate.opsforzset().score("zset7", "pan_junbiao的博客_02"));
    system.out.println("pan_junbiao的博客_03的分数:" + redistemplate.opsforzset().score("zset7", "pan_junbiao的博客_03"));
}

执行结果:

5.8 long removerange(k key, long start, long end)

移除指定索引位置的成员,有序集合成员按照分数值递增(从小到大)顺序排列。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void zset8()
{
    zsetoperations.typedtuple<string> objecttypedtuple1 = new defaulttypedtuple<>("pan_junbiao的博客_01",9.6);
    zsetoperations.typedtuple<string> objecttypedtuple2 = new defaulttypedtuple<>("pan_junbiao的博客_02",1.5);
    zsetoperations.typedtuple<string> objecttypedtuple3 = new defaulttypedtuple<>("pan_junbiao的博客_03",7.4);
 
    set<zsetoperations.typedtuple<string>> tuples = new hashset<zsetoperations.typedtuple<string>>();
    tuples.add(objecttypedtuple1);
    tuples.add(objecttypedtuple2);
    tuples.add(objecttypedtuple3);
 
    system.out.println(redistemplate.opsforzset().add("zset8", tuples));
    system.out.println(redistemplate.opsforzset().range("zset8", 0, -1));
    system.out.println(redistemplate.opsforzset().removerange("zset8", 1, 5));
    system.out.println(redistemplate.opsforzset().range("zset8", 0, -1));
}

执行结果:

5.9 cursor<zsetoperations.typedtuple<v>> scan(k key, scanoptions options)

遍历 zset。具体用法见以下代码:

@autowired
private redistemplate redistemplate;
 
@test
public void zset9()
{
    zsetoperations.typedtuple<string> objecttypedtuple1 = new defaulttypedtuple<>("pan_junbiao的博客_01",9.6);
    zsetoperations.typedtuple<string> objecttypedtuple2 = new defaulttypedtuple<>("pan_junbiao的博客_02",1.5);
    zsetoperations.typedtuple<string> objecttypedtuple3 = new defaulttypedtuple<>("pan_junbiao的博客_03",7.4);
 
    set<zsetoperations.typedtuple<string>> tuples = new hashset<zsetoperations.typedtuple<string>>();
    tuples.add(objecttypedtuple1);
    tuples.add(objecttypedtuple2);
    tuples.add(objecttypedtuple3);
 
    system.out.println(redistemplate.opsforzset().add("zset9", tuples));
    cursor<zsetoperations.typedtuple<object>> cursor = redistemplate.opsforzset().scan("zset9", scanoptions.none);
    while (cursor.hasnext())
    {
        zsetoperations.typedtuple<object> item = cursor.next();
        system.out.println(item.getvalue() + " 的分数值:" + item.getscore());
    }
}

执行结果:

 到此这篇关于详解springboot使用redistemplate操作redis的5种数据类型的文章就介绍到这了,更多相关springboot使用redistemplate操作redis内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《详解SpringBoot使用RedisTemplate操作Redis的5种数据类型.doc》

下载本文的Word格式文档,以方便收藏与打印。