Spring Data Redis使用方式

[复制链接]
admin 发表于 2025-9-18 08:55:04 | 显示全部楼层 |阅读模式
Spring Data Redis使用方式

1,进入到sky-server模块
导入Spring Data Redis的maven坐标(已完成)
  1. <dependency>
  2.      <groupId>org.springframework.boot</groupId>
  3.      <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>
复制代码

2). 配置Redis数据源
在application-dev.yml中添加
  1. sky:
  2.   redis:
  3.     host: localhost
  4.     port: 6379
  5.     password: 123456
  6.     database: 10
复制代码
解释说明:
database:指定使用Redis的哪个数据库,Redis服务启动后默认有16个数据库,编号分别是从0到15,不写默认为0。
可以通过修改Redis配置文件来指定数据库的数量。
在application.yml中添加读取application-dev.yml中的相关Redis配置
  1. spring:
  2.   profiles:
  3.     active: dev
  4.   redis:
  5.     host: ${sky.redis.host}
  6.     port: ${sky.redis.port}
  7.     password: ${sky.redis.password}
  8.     database: ${sky.redis.database}
复制代码
3). 编写配置类,创建RedisTemplate对象
  1. package com.sky.config;

  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.data.redis.connection.RedisConnectionFactory;
  6. import org.springframework.data.redis.core.RedisTemplate;
  7. import org.springframework.data.redis.serializer.StringRedisSerializer;

  8. @Configuration
  9. @Slf4j
  10. public class RedisConfiguration {

  11.     @Bean
  12.     public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
  13.         log.info("开始创建redis模板对象...");
  14.         RedisTemplate redisTemplate = new RedisTemplate();
  15.         //设置redis的连接工厂对象
  16.         redisTemplate.setConnectionFactory(redisConnectionFactory);
  17.         //设置redis key的序列化器
  18.         redisTemplate.setKeySerializer(new StringRedisSerializer());
  19.         return redisTemplate;
  20.     }
  21. }
复制代码
解释说明:
当前配置类不是必须的,因为 Spring Boot 框架会自动装配 RedisTemplate 对象,但是默认的key序列化器为
JdkSerializationRedisSerializer,导致我们存到Redis中后的数据和原始数据有差别,故设置为
StringRedisSerializer序列化器。

4). 通过RedisTemplate对象操作Redis
在test下新建测试类
  1. package com.sky.test;

  2. import org.junit.jupiter.api.Test;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.boot.test.context.SpringBootTest;
  5. import org.springframework.data.redis.core.*;

  6. @SpringBootTest
  7. public class SpringDataRedisTest {
  8.     @Autowired
  9.     private RedisTemplate redisTemplate;

  10.     @Test
  11.     public void testRedisTemplate(){
  12.         System.out.println(redisTemplate);
  13.         //string数据操作
  14.         ValueOperations valueOperations = redisTemplate.opsForValue();
  15.         //hash类型的数据操作
  16.         HashOperations hashOperations = redisTemplate.opsForHash();
  17.         //list类型的数据操作
  18.         ListOperations listOperations = redisTemplate.opsForList();
  19.         //set类型数据操作
  20.         SetOperations setOperations = redisTemplate.opsForSet();
  21.         //zset类型数据操作
  22.         ZSetOperations zSetOperations = redisTemplate.opsForZSet();
  23.     }
  24. }
复制代码
1.jpg
1). 操作字符串类型数据
  1. /**
  2.      * 操作字符串类型的数据
  3.      */
  4.     @Test
  5.     public void testString(){
  6.         // set get setex setnx
  7.         redisTemplate.opsForValue().set("name","小明");
  8.         String city = (String) redisTemplate.opsForValue().get("name");
  9.         System.out.println(city);
  10.         redisTemplate.opsForValue().set("code","1234",3, TimeUnit.MINUTES);
  11.         redisTemplate.opsForValue().setIfAbsent("lock","1");
  12.         redisTemplate.opsForValue().setIfAbsent("lock","2");
  13.     }
复制代码
2). 操作哈希类型数据
  1. /**
  2.      * 操作哈希类型的数据
  3.      */
  4.     @Test
  5.     public void testHash(){
  6.         //hset hget hdel hkeys hvals
  7.         HashOperations hashOperations = redisTemplate.opsForHash();

  8.         hashOperations.put("100","name","tom");
  9.         hashOperations.put("100","age","20");

  10.         String name = (String) hashOperations.get("100", "name");
  11.         System.out.println(name);

  12.         Set keys = hashOperations.keys("100");
  13.         System.out.println(keys);

  14.         List values = hashOperations.values("100");
  15.         System.out.println(values);

  16.         hashOperations.delete("100","age");
  17.     }
复制代码
3). 操作列表类型数据
  1. /**
  2.      * 操作列表类型的数据
  3.      */
  4.     @Test
  5.     public void testList(){
  6.         //lpush lrange rpop llen
  7.         ListOperations listOperations = redisTemplate.opsForList();

  8.         listOperations.leftPushAll("mylist","a","b","c");
  9.         listOperations.leftPush("mylist","d");

  10.         List mylist = listOperations.range("mylist", 0, -1);
  11.         System.out.println(mylist);

  12.         listOperations.rightPop("mylist");

  13.         Long size = listOperations.size("mylist");
  14.         System.out.println(size);
  15.     }
复制代码
4). 操作集合类型数据
  1. /**
  2.      * 操作集合类型的数据
  3.      */
  4.     @Test
  5.     public void testSet(){
  6.         //sadd smembers scard sinter sunion srem
  7.         SetOperations setOperations = redisTemplate.opsForSet();

  8.         setOperations.add("set1","a","b","c","d");
  9.         setOperations.add("set2","a","b","x","y");

  10.         Set members = setOperations.members("set1");
  11.         System.out.println(members);

  12.         Long size = setOperations.size("set1");
  13.         System.out.println(size);

  14.         Set intersect = setOperations.intersect("set1", "set2");
  15.         System.out.println(intersect);

  16.         Set union = setOperations.union("set1", "set2");
  17.         System.out.println(union);

  18.         setOperations.remove("set1","a","b");
  19.     }
复制代码
5). 操作有序集合类型数据
  1. /**
  2.      * 操作有序集合类型的数据
  3.      */
  4.     @Test
  5.     public void testZset(){
  6.         //zadd zrange zincrby zrem
  7.         ZSetOperations zSetOperations = redisTemplate.opsForZSet();

  8.         zSetOperations.add("zset1","a",10);
  9.         zSetOperations.add("zset1","b",12);
  10.         zSetOperations.add("zset1","c",9);

  11.         Set zset1 = zSetOperations.range("zset1", 0, -1);
  12.         System.out.println(zset1);

  13.         zSetOperations.incrementScore("zset1","c",10);

  14.         zSetOperations.remove("zset1","a","b");
  15.     }
复制代码
6). 通用命令操作
  1. /**
  2.      * 通用命令操作
  3.      */
  4.     @Test
  5.     public void testCommon(){
  6.         //keys exists type del
  7.         Set keys = redisTemplate.keys("*");
  8.         System.out.println(keys);

  9.         Boolean name = redisTemplate.hasKey("name");
  10.         Boolean set1 = redisTemplate.hasKey("set1");

  11.         for (Object key : keys) {
  12.             DataType type = redisTemplate.type(key);
  13.             System.out.println(type.name());
  14.         }

  15.         redisTemplate.delete("mylist");
  16.     }
复制代码
测试
  1. package com.sky.test;

  2. import org.junit.jupiter.api.Test;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.boot.test.context.SpringBootTest;
  5. import org.springframework.data.redis.connection.DataType;
  6. import org.springframework.data.redis.core.*;

  7. import java.util.List;
  8. import java.util.Set;
  9. import java.util.concurrent.TimeUnit;

  10. @SpringBootTest
  11. public class SpringDataRedisTest {
  12.     @Autowired
  13.     private RedisTemplate redisTemplate;

  14.     @Test
  15.     public void testRedisTemplate(){
  16.         System.out.println(redisTemplate);
  17.     }

  18.     /**
  19.      * 操作字符串类型的数据
  20.      */
  21.     @Test
  22.     public void testString(){
  23.         // set get setex setnx
  24.         redisTemplate.opsForValue().set("name","小明");
  25.         String city = (String) redisTemplate.opsForValue().get("name");
  26.         System.out.println(city);
  27.         redisTemplate.opsForValue().set("code","1234",3, TimeUnit.MINUTES);
  28.         redisTemplate.opsForValue().setIfAbsent("lock","1");
  29.         redisTemplate.opsForValue().setIfAbsent("lock","2");
  30.     }
  31. }
复制代码
1.jpg
网站建设,公众号小程序开发,多商户单商户小程序制作,高端系统定制开发,App软件开发联系我们【手机/微信:17817817816
 楼主| admin 发表于 2025-9-18 14:11:40 | 显示全部楼层
实际开发中案例:

  1. package com.sky.controller.admin;

  2. import com.sky.result.Result;
  3. import io.swagger.annotations.Api;
  4. import io.swagger.annotations.ApiOperation;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.data.redis.core.RedisTemplate;
  8. import org.springframework.web.bind.annotation.*;

  9. @RestController("adminShopController")
  10. @RequestMapping("/admin/shop")
  11. @Api(tags = "店铺相关接口")
  12. @Slf4j
  13. public class ShopController {

  14.     public static final String KEY = "SHOP_STATUS";

  15.     @Autowired
  16.     private RedisTemplate redisTemplate;

  17.     /**
  18.      * 设置店铺的营业状态
  19.      * @param status
  20.      * @return
  21.      */
  22.     @PutMapping("/{status}")
  23.     @ApiOperation("设置店铺的营业状态")
  24.     public Result setStatus(@PathVariable Integer status){
  25.         log.info("设置店铺的营业状态为:{}",status == 1 ? "营业中" : "打烊中");
  26.         redisTemplate.opsForValue().set(KEY,status);
  27.         return Result.success();
  28.     }

  29.     /**
  30.      * 获取店铺的营业状态
  31.      * @return
  32.      */
  33.     @GetMapping("/status")
  34.     @ApiOperation("获取店铺的营业状态")
  35.     public Result<Integer> getStatus(){
  36.         Integer status = (Integer) redisTemplate.opsForValue().get(KEY);
  37.         log.info("获取到店铺的营业状态为:{}",status == 1 ? "营业中" : "打烊中");
  38.         return Result.success(status);
  39.     }
  40. }
复制代码


网站建设,公众号小程序开发,多商户单商户小程序制作,高端系统定制开发,App软件开发联系我们【手机/微信:17817817816
微信扫码

网站建设,公众号小程序开发,商城小程序,系统定制开发,App软件开发等

粤ICP备2024252464号

在本版发帖
微信扫码
QQ客服返回顶部
快速回复 返回顶部 返回列表