当前位置: 首页 > news >正文

SpringBoot 2.x 整合 Redis

整合

1)添加依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 如果没有使用下面给出的工具类,那么就不需要引入 -->
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.2.4</version>
</dependency>

2)application.xml 配置

spring:redis:database: 0# ip 或者域名host: 192.168.224.128# 密码password: TO6Md91Advf# redis 默认端口是 6379port: 6379

3)配置 RedisTemplate

这里替换序列化器是因为 , RedisTemplate 默认的序列化方案是 JdkSerializationRedisSerializer,它将对象序列化为字节数组。

@Configuration
public class RedisTemplateConfig {@Beanpublic RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(redisConnectionFactory);// 自定义的string序列化器StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();// jackson 序列化器GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();// kv 序列化redisTemplate.setKeySerializer(stringRedisSerializer);redisTemplate.setValueSerializer(jsonRedisSerializer);// hash 序列化redisTemplate.setHashKeySerializer(stringRedisSerializer);redisTemplate.setHashValueSerializer(jsonRedisSerializer);redisTemplate.afterPropertiesSet();return redisTemplate;}
}

使用例子

1)Redis 使用工具类

public class RedisUtil {@SuppressWarnings("unchecked")private static RedisTemplate<Object, Object> redisTemplate = SpringUtil.getBean("redisTemplate", RedisTemplate.class);/*** 指定键的值增加* @param key 键* @param num  要增加的数* @return*/public static int incrementInt(String key,int num){Long increment = redisTemplate.opsForValue().increment(key,num);return increment.intValue();}/*** 指定缓存失效时间** @param key  键* @param time 时间(秒)*/public static void expire(String key, long time) {if (time > 0) {redisTemplate.expire(key, time, TimeUnit.SECONDS);}}public static long getExpire(String key){return redisTemplate.getExpire(key);}/*** 普通缓存获取** @param key 键* @return 值*/public static Object get(String key) {return key == null ? null : redisTemplate.opsForValue().get(key);}/*** 获取数据** @param key 键* @return 对应的键值*/public static Map<Object, Object> getMap(String key) {return redisTemplate.opsForHash().entries(key);}/*** 缓存放入** @param key   键* @param value 值*/public static void set(String key, Object value) {redisTemplate.opsForValue().set(key, value);}/*** 缓存放入** @param key   键* @param value 值* @param time  时间(秒)*/public static void set(String key, Object value, long time) {if (time > 0) {redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);} else {set(key, value);}}/*** Map 缓存放入* @param key  键* @param map  对应多个键值*/public static void putMap(String key, Map<Object, Object> map) {redisTemplate.opsForHash().putAll(key, map);}/*** Map 缓存放入** @param key  键* @param map  对应多个键值* @param time 时间(秒)*/public static void putMap(String key, Map<Object, Object> map, long time) {redisTemplate.opsForHash().putAll(key, map);if (time > 0) {expire(key, time);}}/*** list 缓存放入,尾部添加* @param key 键* @param value 值*/public static void pushList(String key, Object value) {redisTemplate.opsForList().rightPush(key, value);}/*** list 缓存放入,尾部添加, 批量存放 list* @param key* @param list*/public static void pushListAll(String key, List<Object> list) {if (list != null){redisTemplate.opsForList().rightPushAll(key, list);}}/*** 通过 key 获取 list*/public static List<Object> getAllList(String key){return redisTemplate.opsForList().range(key, 0, -1);}}

2)TestRdsController

如果没有使用 lomback,swagger,可以将对应的注解删除掉

/*** 用于测试 rds* @author fei**/
@Slf4j
@RestController
@RequestMapping("/")
@Api(value = "测试 RDS API", tags = {"测试 RDS API"})
public class TestRdsController extends BaseController {@AutowiredTestRdsService testRdsService;@GetMapping(value = "/rds/setString")@OperationLog(name="set String",type = OperationLogType.CREATE)@ApiOperation(value = "set String")public String rdsSetString(@ApiParam(value = "key", required = true) @RequestParam(value = "key")String key,@ApiParam(value = "value", required = true) @RequestParam(value = "value")String value) {testRdsService.rdsSetString(key, value);return "操作成功!");}@GetMapping(value = "/rds/getString")@ApiOperation(value = "get String")public String rdsGetString(@ApiParam(value = "key", required = true) @RequestParam(value = "key")String key) {String value = testRdsService.rdsGetString(key);return value;}@GetMapping(value = "/rds/putMap")@ApiOperation(value = "putMap")public String rdsPutMap(@ApiParam(value = "key", required = true) @RequestParam(value = "key") String key,@ApiParam(value = "name", required = true) @RequestParam(value = "name") String name,@ApiParam(value = "age", required = true) @RequestParam(value = "age") Integer age) {testRdsService.putMap(key, name, age);return "操作成功";}@GetMapping(value = "/rds/getMap")@ApiOperation(value = "getMap")public Map<Object, Object> getMap(@ApiParam(value = "key", required = true) @RequestParam(value = "key") String key) {Map<Object, Object> map = testRdsService.getMap(key);return map;}@GetMapping(value = "/rds/pushList")@ApiOperation(value = "list 缓存放入,尾部添加")public String pushList(@ApiParam(value = "key", required = true) @RequestParam(value = "key") String key,@ApiParam(value = "value", required = true) @RequestParam(value = "value") Object value) {testRdsService.pushList(key, value);return "操作成功";}@GetMapping(value = "/rds/pushAllList")@ApiOperation(value = "将list数据全部放入 list 缓存")public String pushAllList(@ApiParam(value = "key", required = true) @RequestParam(value = "key") String key,@ApiParam(value = "list", required = true) @RequestParam(value = "list") List<Object> list) {testRdsService.pushListAll(key, list);return "操作成功";}@GetMapping(value = "/rds/getAllList")@ApiOperation(value = "通过 key 获取所有 list")public List<Object> getAllList(@ApiParam(value = "key", required = true) @RequestParam(value = "key") String key) {List<Object> allList = testRdsService.getAllList(key);return allList;}}

3)TestRdsService

/**** @author fei* @create 2024/11/20 9:12**/
public interface TestRdsService {void rdsSetString(String key, String value);String rdsGetString(String key);void putMap(String key, String name, Integer age);Map<Object, Object> getMap(String key);void pushList(String key, Object value);void pushListAll(String key, List<Object> list);List<Object> getAllList(String key);}

4)TestRdsServiceImpl

/**** @author fei* @create 2024/11/20 9:12**/
@Service
public class TestRdsServiceImpl implements TestRdsService {@Overridepublic void rdsSetString(String key, String value) {RedisUtil.set(key, value);}@Overridepublic String rdsGetString(String key) {Object o = RedisUtil.get(key);if (o == null){return "";}return (String)o;}@Overridepublic void putMap(String key, String name, Integer age) {Map<Object, Object> map = new HashMap<>();map.put("name", name);map.put("age", age);RedisUtil.putMap(key, map, 10000);}@Overridepublic Map<Object, Object> getMap(String key) {return RedisUtil.getMap(key);}@Overridepublic void pushList(String key, Object value) {RedisUtil.pushList(key, value);}@Overridepublic void pushListAll(String key, List<Object> list) {RedisUtil.pushListAll(key, list);}@Overridepublic List<Object> getAllList(String key) {return RedisUtil.getAllList(key);}}

5)测试

最后可以使用 swagger 或者 Apifox 等工具调用接口测试,或者直接写个测试用例也可以

http://www.lryc.cn/news/488756.html

相关文章:

  • React的API✅
  • 什么是全渠道客服中心?都包括哪些电商平台?
  • Jtti:如何知晓服务器的压力上限?具体的步骤和方法
  • 贪心算法(1)
  • SpringBoot,IOC,DI,分层解耦,统一响应
  • 目标驱动学习python动力
  • 力扣-Hot100-回溯【算法学习day.39】
  • 小熊派Nano接入华为云
  • 【linux硬件操作系统】计算机硬件常见硬件故障处理
  • 谈学生公寓安全用电系统的涉及方案
  • 自动语音识别(ASR)与文本转语音(TTS)技术的应用与发展
  • Go 语言数组
  • 13. 【.NET 8 实战--孢子记账--从单体到微服务】--简易权限--完善TODO标记的代码
  • 深入剖析Java内存管理:机制、优化与最佳实践
  • 【Amazon】亚马逊云科技Amazon DynamoDB 实践Amazon DynamoDB
  • Qt-常用的显示类控件
  • LabVIEW内燃机缸压采集与分析
  • 【Linux学习】【Ubuntu入门】1-7 ubuntu下磁盘管理
  • VScode clangd插件安装
  • 【机器学习】- L1L2 正则化操作
  • Logback实战指南:基础知识、实战应用及最佳实践全攻略
  • 基于python的机器学习(三)—— 关联规则与推荐算法
  • 【大模型】LLaMA: Open and Efficient Foundation Language Models
  • 模拟器多开限制ip,如何设置单窗口单ip,每个窗口ip不同
  • hive的存储格式
  • 鸿蒙学习高效开发与测试-应用程序框架(3)
  • 什么命令可以查看数据库中表的结构
  • django基于python 语言的酒店推荐系统
  • 【深度学习|onnx】往onnx中写入训练的超参或者类别等信息,并在推理时读取
  • WebSocket详解、WebSocket入门案例