SpringBoot——实现对Redis五种数据类型的增删改查

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Tair(兼容Redis),内存型 2GB
简介: SpringBoot——实现对Redis五种数据类型的增删改查

文章目录


一、添加Redis依赖

二、application.properties

三、添加配置类

四、测试

TestRedisString

TestRedisList

TestRedisHash

Article

TestRedisSet

TestRedisZSet


一、添加Redis依赖


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

二、application.properties


# 应用名称
spring.application.name=springboot_redis
server.port=8085
#配置Redis,redis的host是虚拟机服务器上的IP地址,端口6379
spring.redis.host=127.0.0.1
spring.redis.port=6379

三、添加配置类


package com.ljx.springboot_redis.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;
import java.time.Duration;
/**
 * @Author: Ljx
 * @Date: 2021/12/1 13:34
 * @role:
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
    private static final StringRedisSerializer STRING_SERIALIZER = new StringRedisSerializer();
    private static final GenericJackson2JsonRedisSerializer JACKSON__SERIALIZER = new GenericJackson2JsonRedisSerializer();
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        //设置缓存过期时间
        RedisCacheConfiguration redisCacheCfg=RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(1))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(STRING_SERIALIZER))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(JACKSON__SERIALIZER));
        return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheCfg)
                .build();
    }
    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        // 配置redisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        // key序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // value序列化
        redisTemplate.setValueSerializer(JACKSON__SERIALIZER);
        // Hash key序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // Hash value序列化
        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

四、测试


TestRedisString


package com.ljx.springboot_redis;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
 * @Author: Ljx
 * @Date: 2021/12/1 0:52
 * @role:
 */
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
class TestRedisString {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Test
    public void testSet(){
        //向数据库中保存 name heima
        redisTemplate.opsForValue().set("name","heima");
        //相关数据保存 name1 heima1  有效时间为10s
        redisTemplate.opsForValue().set("name1","heima1",10, TimeUnit.SECONDS);
        //替换 heima        heXXa  offset 索引位置是从0开始
        redisTemplate.opsForValue().set("name","XX",2);
        //当key不存在的时候,执行保存操作;当key存在时,什么都不做
        redisTemplate.opsForValue().setIfAbsent("name","heima");
        //批量保存
        Map<String,String> map = new HashMap<>();
        map.put("name2","heima2");
        map.put("name3","heima3");
        map.put("name3","heima3");
        redisTemplate.opsForValue().multiSet(map);
        //追加 当key存在时,会执行追加操作;当key不存在时,会执行保存操作
        redisTemplate.opsForValue().append("name5","heima");
    }
    @Test
    public void testGet(){
        //根据key获取value
        String value = redisTemplate.opsForValue().get("name");
        System.out.println(value);
        //首先根据key获取value,然后再根据value进行截取。从start位置截取到end位置【包含start和end】
        String name = redisTemplate.opsForValue().get("name", 5, 7);
        System.out.println(name);
        //批量获取
        List<String> keys = new ArrayList<>();
        keys.add("name2");
        keys.add("name3");
        keys.add("name4");
        List<String> values = redisTemplate.opsForValue().multiGet(keys);
        for (String s : values) {
            System.out.println(s);
        }
        //根据key获取value的长度
        Long size = redisTemplate.opsForValue().size("name");
        System.out.println(size);
    }
    @Test
    public void testIncrement(){
        redisTemplate.opsForValue().set("age","18");
//        自增1
        redisTemplate.opsForValue().increment("age");
        System.out.println(redisTemplate.opsForValue().get("age"));
//        自增6
        redisTemplate.opsForValue().increment("age",6);
        System.out.println(redisTemplate.opsForValue().get("age"));
//        自减
        redisTemplate.opsForValue().decrement("age");
    }
    //删除
    @Test
    public void testDelete(){
//        单个删除
        redisTemplate.delete("name");
        List<String> list = new ArrayList<>();
        list.add("name2");
        list.add("name3");
        list.add("name4");
//        批量删除
        redisTemplate.delete(list);
    }
}

TestRedisList


package com.ljx.springboot_redis;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.swing.*;
import java.util.List;
/**
 * @Author: Ljx
 * @Date: 2021/12/1 20:24
 * @role:
 */
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class TestRedisList {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    //增加
    @Test
    public void testAdd(){
        //从左边添加一个元素
        redisTemplate.opsForList().leftPush("students","zhangshan");
        //从左边添加多个元素
        redisTemplate.opsForList().leftPush("students","lishi","wangwu");
        //从右边添加一个元素
        redisTemplate.opsForList().rightPush("students","zhangshan1");
        //从右边添加多个元素
        redisTemplate.opsForList().rightPush("students","lishi1","wangwu1");
    }
    @Test
    public void testFind(){
        //根据key和元素索引进行查询
        //0和正数代表从左边开始
        //负数代表从右边开始
        String students = redisTemplate.opsForList().index("students", 1);
        System.out.println(students);
        String students1 = redisTemplate.opsForList().index("students", -1);
        System.out.println(students1);
        //范围查询
        //根据key 【start,end】 包括首尾
        List<String> students2 = redisTemplate.opsForList().range("students", 0, 2);
        for (String s : students2) {
            System.out.println(s);
        }
    }
    //删除
    @Test
    public void testRemove(){
        //从左边删除第一个元素
        String s = redisTemplate.opsForList().leftPop("students");
        //从右边删除第一个元素
        String s1 = redisTemplate.opsForList().rightPop("students");
        //count > 0; 删除左边起第几个等于指定值的元素
        //count < 0; 删除右边起第几个等于指定值的元素
        //count = 0; 删除所有等于value的元素
        //删除左边起第二个wangwu
        redisTemplate.opsForList().remove("students",2,"wangwu");
    }
}

TestRedisHash


package com.ljx.springboot_redis;
import com.ljx.springboot_redis.uesr.Article;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
 * @Author: Ljx
 * @Date: 2021/12/1 13:07
 * @role:
 */
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class TestRedisHash {
    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    public void testPut(){
//        redisTemplate.setKeySerializer(new StringRedisSerializer());
//        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
//        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
        Article article = new Article();
        article.setTitle("title");
        article.setCreateTime(new Date());
        article.setAuthor("lixiang");
        redisTemplate.opsForHash().put("article","1",article);
    }
    @Test
    public void testGet(){
//        redisTemplate.setKeySerializer(new StringRedisSerializer());
//        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
//        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
        //判断hashkey是否存在
//        Boolean article = redisTemplate.opsForHash().hasKey("article", "2");
//        System.out.println(article);
//
//        //根据key和hashkey获取操作
//        Article article1 = (Article) redisTemplate.opsForHash().get("article", "2");
//        System.out.println(article1);
//        //根据key获取所有的hashkey
//        Set<String> set = redisTemplate.opsForHash().keys("article");
//        for (Object s : set) {
//            System.out.println(s);
//        }
        List<Article> articles = redisTemplate.opsForHash().values("article");
        for (Article article : articles) {
            System.out.println(article);
        }
        Map<String,Article> map = redisTemplate.opsForHash().entries("article");
        for (Map.Entry<String, Article> entry : map.entrySet()) {
            System.out.println(entry.getKey()+":"+entry.getValue());
        }
    }
    //删除
    @Test
    public void testDelete(){
        //当hash中的数据全被删除后,整个hash就没了
        redisTemplate.opsForHash().delete("article","1","2");
    }
}

Article


package com.ljx.springboot_redis.uesr;
import javax.xml.crypto.Data;
import java.io.Serializable;
import java.util.Date;
/**
 * @Author: Ljx
 * @Date: 2021/12/1 13:12
 * @role:
 */
public class Article implements Serializable {
    private String author;
    private Data createTime;
    private String title;
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public Data getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Data createTime) {
        this.createTime = createTime;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    @Override
    public String toString() {
        return "Article{" +
                "author='" + author + '\'' +
                ", createTime=" + createTime +
                ", title='" + title + '\'' +
                '}';
    }
    public void setCreateTime(Date date) {
    }
}

TestRedisSet


package com.ljx.springboot_redis;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
import java.util.Set;
/**
 * @Author: Ljx
 * @Date: 2021/12/1 20:48
 * @role:
 */
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class TestRedisSet {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    //增加
    @Test
    public void testAdd(){
        redisTemplate.opsForSet().add("Students","zhangsan","lishi","wangwu","Zhangsan");
    }
    //查询
    @Test
    public void testFind(){
        //查询所有元素
        Set<String> students = redisTemplate.opsForSet().members("Students");
        for (String student : students) {
            System.out.println(student);
        }
        //随机获取一个元素
        String students1 = redisTemplate.opsForSet().randomMember("Students");
        System.out.println(students1);
        //随机获取多个元素【可能会重复】
        List<String> list = redisTemplate.opsForSet().randomMembers("Students", 2);
        for (String s : list) {
            System.out.println(s);
        }
    }
    //删除
    @Test
    public void testRemove(){
        //移除元素,并返回移除成功个数
        Long remove = redisTemplate.opsForSet().remove("Students", "zhangsan", "wangwu");
        System.out.println(remove);
        //随机移除指定集合中的多少个元素
        List<String> students = redisTemplate.opsForSet().pop("Students", 2);
        for (String student : students) {
            System.out.println(student);
        }
    }
    //多集合操作
    @Test
    public void testMoreSet(){
        redisTemplate.opsForSet().add("names1","zhangsan","li","wangwu");
        redisTemplate.opsForSet().add("names2","zhangsan","li","zhaoliu");
        //取交集
        Set<String> intersect = redisTemplate.opsForSet().intersect("names1", "names2");
        for (String s : intersect) {
            System.out.println(s);
        }
        //取并集
        Set<String> union = redisTemplate.opsForSet().union("names1", "names2");
        for (String s : union) {
            System.out.println(s);
        }
        //取差集[第一个集合中存在,但第二个集合中不存在的元素]
        Set<String> difference = redisTemplate.opsForSet().difference("names2", "names1");
        for (String s : difference) {
            System.out.println(s);
        }
    }
}

TestRedisZSet


package com.ljx.springboot_redis;
import org.junit.Before;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Set;
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
class TestRedisZSet {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Test
    public void testAdd(){
        redisTemplate.opsForZSet().add("student","wangwu",60);
        redisTemplate.opsForZSet().add("student","lishi",100);
        redisTemplate.opsForZSet().add("student","zhangshan",90);
    }
//    分数的增减
    @Test
    public void testScore(){
        // 增加分数
        redisTemplate.opsForZSet().incrementScore("student","wangwu",30);
        // 减少分数
        redisTemplate.opsForZSet().incrementScore("student","wangwu",-50);
    }
    // 查询一个元素的信息
    @Test
    public void testFindOne(){
        //查询一个元素的分数
        Double score = redisTemplate.opsForZSet().score("student", "wangwu");
        System.out.println(score);
        //查询一个元素在集合中的排名  排名从0开始
        Long rank = redisTemplate.opsForZSet().rank("student", "zhangshan");
        System.out.println(rank);
    }
    //根据区间获取列表
    @Test
    public void testFindList(){
        //根据排名区间获取元素列表
        Set<String> students = redisTemplate.opsForZSet().range("student",0,2);
        for (String student : students) {
            System.out.println(student);
        }
        System.out.println("-------------");
        Set<ZSetOperations.TypedTuple<String>> student = redisTemplate.opsForZSet().rangeWithScores("student", 0, 2);
        for (ZSetOperations.TypedTuple<String> stringTypedTuple : student) {
            System.out.println(stringTypedTuple.getValue()+"同学,得了"+stringTypedTuple.getScore()+"分");
        }
        System.out.println("-----------------------------");
        //根据排名区间获取元素列表
        Set<String> students1 = redisTemplate.opsForZSet().rangeByScore("student",50,100);
        for (String student1 : students1) {
            System.out.println(student1);
        }
        System.out.println("-------------");
        Set<ZSetOperations.TypedTuple<String>> student1 = redisTemplate.opsForZSet().rangeByScoreWithScores("student", 50, 100);
        for (ZSetOperations.TypedTuple<String> stringTypedTuple : student1) {
            System.out.println(stringTypedTuple.getValue()+"同学,得了"+stringTypedTuple.getScore()+"分");
        }
    }
    //统计
    @Test
    public void testCount(){
        //统计一个集合中元素
        Long student = redisTemplate.opsForZSet().zCard("student");
        System.out.println(student);
        //根据一个分数区间统计元素数量
        Long count = redisTemplate.opsForZSet().count("student", 50, 100);
        System.out.println(count);
    }
    //删除
    @Test
    public void testRemove(){
        //根据key-value删除 value允许传入多个
        redisTemplate.opsForZSet().remove("student","zhangsan","lisi");
        //根据排名区间删除
        redisTemplate.opsForZSet().removeRange("student",0,1);
        //根据分数区间删除
        redisTemplate.opsForZSet().removeRangeByScore("student",70,90);
    }
}


相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
相关文章
|
6月前
|
NoSQL Java 关系型数据库
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 介绍
本文介绍在 Spring Boot 中集成 Redis 的方法。Redis 是一种支持多种数据结构的非关系型数据库(NoSQL),具备高并发、高性能和灵活扩展的特点,适用于缓存、实时数据分析等场景。其数据以键值对形式存储,支持字符串、哈希、列表、集合等类型。通过将 Redis 与 Mysql 集群结合使用,可实现数据同步,提升系统稳定性。例如,在网站架构中优先从 Redis 获取数据,故障时回退至 Mysql,确保服务不中断。
254 0
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 介绍
|
2月前
|
存储 NoSQL 定位技术
Redis数据类型面试给分情况
Redis常见数据类型包括:string、hash、list、set、zset(有序集合)。此外还包含高级结构如bitmap、hyperloglog、geo。不同场景可选用合适类型,如库存用string,对象存hash,列表用list,去重场景用set,排行用zset,签到用bitmap,统计访问量用hyperloglog,地理位置用geo。
75 5
|
2月前
|
NoSQL Java Redis
Redis基本数据类型及Spring Data Redis应用
Redis 是开源高性能键值对数据库,支持 String、Hash、List、Set、Sorted Set 等数据结构,适用于缓存、消息队列、排行榜等场景。具备高性能、原子操作及丰富功能,是分布式系统核心组件。
328 2
|
6月前
|
缓存 NoSQL Java
基于SpringBoot的Redis开发实战教程
Redis在Spring Boot中的应用非常广泛,其高性能和灵活性使其成为构建高效分布式系统的理想选择。通过深入理解本文的内容,您可以更好地利用Redis的特性,为应用程序提供高效的缓存和消息处理能力。
475 79
|
7月前
|
NoSQL Java Redis
Springboot使用Redis实现分布式锁
通过这些步骤和示例,您可以系统地了解如何在Spring Boot中使用Redis实现分布式锁,并在实际项目中应用。希望这些内容对您的学习和工作有所帮助。
646 83
|
3月前
|
机器学习/深度学习 数据采集 人机交互
springboot+redis互联网医院智能导诊系统源码,基于医疗大模型、知识图谱、人机交互方式实现
智能导诊系统基于医疗大模型、知识图谱与人机交互技术,解决患者“知症不知病”“挂错号”等问题。通过多模态交互(语音、文字、图片等)收集病情信息,结合医学知识图谱和深度推理,实现精准的科室推荐和分级诊疗引导。系统支持基于规则模板和数据模型两种开发原理:前者依赖人工设定症状-科室规则,后者通过机器学习或深度学习分析问诊数据。其特点包括快速病情收集、智能病症关联推理、最佳就医推荐、分级导流以及与院内平台联动,提升患者就诊效率和服务体验。技术架构采用 SpringBoot+Redis+MyBatis Plus+MySQL+RocketMQ,确保高效稳定运行。
225 0
|
6月前
|
存储 人工智能 NoSQL
SpringBoot整合Redis、ApacheSolr和SpringSession
本文介绍了如何使用SpringBoot整合Redis、ApacheSolr和SpringSession。SpringBoot以其便捷的配置方式受到开发者青睐,通过引入对应的starter依赖,可轻松实现功能整合。对于Redis,可通过配置RedisSentinel实现高可用;SpringSession则提供集群Session管理,支持多种存储方式如Redis;整合ApacheSolr时,借助Zookeeper搭建SolrCloud提高可用性。文中详细说明了各组件的配置步骤与代码示例,方便开发者快速上手。
105 11
|
6月前
|
NoSQL Java API
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Spring Boot 集成 Redis
本文介绍了在Spring Boot中集成Redis的方法,包括依赖导入、Redis配置及常用API的使用。通过导入`spring-boot-starter-data-redis`依赖和配置`application.yml`文件,可轻松实现Redis集成。文中详细讲解了StringRedisTemplate的使用,适用于字符串操作,并结合FastJSON将实体类转换为JSON存储。还展示了Redis的string、hash和list类型的操作示例。最后总结了Redis在缓存和高并发场景中的应用价值,并提供课程源代码下载链接。
1566 0
|
6月前
|
NoSQL Java Redis
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 安装
本教程介绍在 VMware 虚拟机(CentOS 7)或阿里云服务器中安装 Redis 的过程,包括安装 gcc 编译环境、下载 Redis(官网或 wget)、解压安装、修改配置文件(如 bind、daemonize、requirepass 等设置)、启动 Redis 服务及测试客户端连接。通过 set 和 get 命令验证安装是否成功。适用于初学者快速上手 Redis 部署。
125 0
|
6月前
|
NoSQL Redis
Redis的常用数据类型有哪些 ?
Redis 有 5 种基础数据结构,它们分别是:string(字符串)、list(列表)、hash(字典)、set(集 合) 和 zset(有序集合)