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

SpringBoot入门实战(第四篇:Redis集成配置)

🤟致敬读者

  • 🟩感谢阅读🟦笑口常开🟪生日快乐⬛早点睡觉

📘博主相关

  • 🟧博主信息🟨博客首页🟫专栏推荐🟥活动信息

文章目录

  • SpringBoot入门实战(第四篇:Redis集成配置)
    • 1. 依赖引入(pom.xml)
    • 2. 参数配置(application.yml)
    • 3. 配置类(RedisConfig.java)
    • 4. 工具类(RedisUtils.java)
    • 5. 接口代码
    • 6. 调用测试


📃文章前言

  • 🔷文章均为学习工作中整理的笔记。
  • 🔶如有错误请指正,共同学习进步。

SpringBoot入门实战(第四篇:Redis集成配置)

SpringBoot入门实战系列篇专栏
SpringBoot入门实战(第一篇:环境准备和项目初始化)
SpringBoot入门实战(第二篇:MySQL集成配置)
SpringBoot入门实战(第三篇:MyBatis集成配置,自动生成代码配置)
SpringBoot入门实战(第四篇:Redis集成配置)
SpringBoot入门实战(第五篇:项目接口-用户管理)
SpringBoot入门实战(第六篇:项目接口-登录)
SpringBoot入门实战(第七篇:项目接口-商品管理)
SpringBoot入门实战(第八篇:项目接口-订单管理)完结篇
SpringBoot入门实战(项目搭建、配置、功能接口实现等一篇通关)


1. 依赖引入(pom.xml)

所需依赖

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

2. 参数配置(application.yml)

配置文件中配置redis相关参数
application.yml

spring:redis:host: 127.0.0.1port: 6379password: xh.1234database: 0jedis:pool:max-idle: 8min-idle: 1max-active: 8max-wait: -1timeout: 20000

3. 配置类(RedisConfig.java)

在com.xh.common.config包下创建redis配置类RedisConfig.java

package com.xh.common.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** @func:* @author: LiBai* @version: v1.0* @createTime: 2025/4/17 9:47*/
@Configuration
public class RedisConfig {@Bean@SuppressWarnings("all")public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory connectionFactory){RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(connectionFactory);StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();template.setKeySerializer(stringRedisSerializer);template.setValueSerializer(stringRedisSerializer);GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();template.setHashKeySerializer(stringRedisSerializer);template.setHashValueSerializer(genericJackson2JsonRedisSerializer);template.afterPropertiesSet();return template;}
}

4. 工具类(RedisUtils.java)

在com.xh.common.utils包下创建Redis工具类RedisUtils.java

package com.xh.common.utils;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;/*** @func:* @author: LiBai* @version: v1.0* @createTime: 2025/4/17 9:46*/
@Component
public class RedisUtils {@AutowiredRedisTemplate<String, Object> redisTemplate;public static RedisTemplate<String, Object> _redisTemplate;@PostConstructpublic void init(){_redisTemplate = redisTemplate;}// =============================common============================/** 设置失效时间 */public static void setexpire(String key, long time) {_redisTemplate.expire(key, time, TimeUnit.SECONDS);}/** 获取过期时间 */public static long getexpire(String key) {return _redisTemplate.getExpire(key, TimeUnit.SECONDS);}/** 判断key是否存在 */public static boolean haskey(String key) {return _redisTemplate.hasKey(key);}/** 查询key */public static Set<String> search(String keyword){return _redisTemplate.keys(keyword);}/** 删除key */@SuppressWarnings("unchecked")public static void delete(String... key) {if (key.length == 1) {_redisTemplate.delete(key[0]);} else {_redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));}}// =============================String============================/** 获取普通类型缓存 */public static Object get(String key) {return key == null ? null : _redisTemplate.opsForValue().get(key);}/** 设置普通类型缓存 */public static void set(String key, Object value) {_redisTemplate.opsForValue().set(key, value);}/** 设置普通类型缓存 带失效时间*/public static void set(String key, Object value, long time) {_redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);}// =============================Hash==============================/** 从hashmap中返回键位item的值 */public static Object hget(String key, String item) {return _redisTemplate.opsForHash().get(key, item);}/** 向hashmap写入一个键值对 */public static void hset(String key, String item, Object value) {_redisTemplate.opsForHash().put(key, item, value);}/** 从hashmap中删除名为item的key */public static void hremove(String key, Object... item) {_redisTemplate.opsForHash().delete(key, item);}/** 判断hashmap里面是否包含item的key */public static boolean hhasitem(String key, String item) {return _redisTemplate.opsForHash().hasKey(key, item);}/** 一次性从hashmap中返回所有的键值对 */public static Map<Object, Object> hmget(String key) {return _redisTemplate.opsForHash().entries(key);}/** 向hashmap写入多个个键值对 */public static void hmset(String key, Map<String, Object> map) {_redisTemplate.opsForHash().putAll(key, map);}// =============================List==============================/** 返回一个list的长度 */public static long lgetsize(String key) {return _redisTemplate.opsForList().size(key);}/** 返回一个list 给定开始index和结束index */public static List<Object> lget(String key, long start, long end) {return _redisTemplate.opsForList().range(key, start, end);}/*** jwh-20241022-获取列表第一个元素并从redis中移除* @param key redis数据的键* @return 返回移除的数据*/public static Object lGetPop(String key) {return _redisTemplate.opsForList().leftPop(key);}/** 通过索引index获取list中的值 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素 */public static Object lgetindex(String key, long index) {return _redisTemplate.opsForList().index(key, index);}/** 将list放入缓存 */public static void lset(String key, Object value) {_redisTemplate.opsForList().rightPush(key, value);}/** 将list放入缓存 */public static void lset(String key, List<Object> value) {_redisTemplate.opsForList().rightPushAll(key, value);}/** 根据索引修改list中的某条数据 */public static void lupdateindex(String key, long index, Object value) {_redisTemplate.opsForList().set(key, index, value);}/** 移除N个值为value */public static long lRemove(String key, long count, Object value) {return _redisTemplate.opsForList().remove(key, count, value);}// =============================Set===============================/** 获取set的长度 */public static long sgetsetsize(String key) {return _redisTemplate.opsForSet().size(key);}/** 获取set中的全部元素 */public static Set<Object> sget(String key) {return _redisTemplate.opsForSet().members(key);}/** 判断set中是否包含value */public static boolean shaskey(String key, Object value) {return _redisTemplate.opsForSet().isMember(key, value);}/** set中添加对象*/public static long sset(String key, Object... values) {return _redisTemplate.opsForSet().add(key, values);}/** 删除set中的values元素*/public static long sremove(String key, Object... values) {return _redisTemplate.opsForSet().remove(key, values);}}

5. 接口代码

创建接口,新增数据到redis中,以存储字符串类型数据为例
com.xh.user.controller包下创建RedisTest.java

package com.xh.user.controller;import com.alibaba.fastjson.JSONObject;
import com.xh.common.utils.RedisUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** @func:* @author: LiBai* @version: v1.0* @createTime: 2025/4/17 9:59*/
@RestController
@RequestMapping(value = "/xh/v1/redis")
public class RedisTest {@RequestMapping(value = "/strAdd")public JSONObject strAdd(){RedisUtils.set("RedisTest001","this is a test for redis util");System.out.println("this is a test for redis util");return null;}
}

6. 调用测试

请求地址

127.0.0.1:8088/xh/v1/redis/strAdd

请求参数为空
在这里插入图片描述

调用后并查看redis客户端
在这里插入图片描述
可以看到数据已存入,其余方法类似

以上就是spring boot集成redis内容


📜文末寄语

  • 🟠关注我,获取更多内容。
  • 🟡技术动态、实战教程、问题解决方案等内容持续更新中。
  • 🟢《全栈知识库》技术交流和分享社区,集结全栈各领域开发者,期待你的加入。
  • 🔵​加入开发者的《专属社群》,分享交流,技术之路不再孤独,一起变强。
  • 🟣点击下方名片获取更多内容🍭🍭🍭👇

相关文章:

  • 08前端项目----升序/降序
  • 资本怪兽贝莱德投资数据分析报告-独家
  • 基于OpenCV的骨骼手势识别分析系统
  • 仓颉造字,亦可造AI代理
  • `std::cout << xxx`
  • 虚幻基础:动画k帧
  • 抱佛脚之学SSM四
  • C++_并发编程_thread_01_基本应用
  • Python 之 pyecharts 使用
  • Yocto项目实战教程-第7章定制镜像菜谱与内核菜谱-7.2小节-定制应用程序
  • 使用Python+OpenCV将多级嵌套文件夹下的视频文件抽帧为JPG图片
  • AI 模型可靠性危机:DeepSeek 输出异常的技术归因与防范实践
  • 电源上电回勾现象
  • 【c语言】指针和数组笔试题解析
  • 常见数据库关键字示例 SQL 及执行顺序分析(带详细注释)
  • LX10-MDK的使用技巧
  • Qt基础006(事件)
  • 全国 OSM 数据集(2014 - 2024 年)
  • 【刷题Day23】线程和进程(浅)
  • 深度学习-全连接神经网络-3
  • 泡泡玛特一季度整体收入同比增超1.6倍,海外收入增近5倍
  • 外贸50城,谁在“扛大旗”?
  • 翁东华卸任文和友小龙虾公司董事,此前抢镜“甲亢哥”惹争议
  • 上海34年“老外贸”张斌:穿越风暴,必须靠过硬的核心竞争力
  • 外汇局:将持续强化外汇形势监测,保持汇率弹性,坚决对市场顺周期行为进行纠偏
  • 外交部:制裁在涉港问题上表现恶劣的美方人士是对等反制