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

Spring Boot 中使用 Redis:从入门到实战

🌟 前言

欢迎来到我的技术小宇宙!🌌 这里不仅是我记录技术点滴的后花园,也是我分享学习心得和项目经验的乐园。📚 无论你是技术小白还是资深大牛,这里总有一些内容能触动你的好奇心。🔍

  • 🤖 洛可可白:个人主页

  • 🔥 个人专栏:✅前端技术 ✅后端技术

  • 🏠 个人博客:洛可可白博客

  • 🐱 代码获取:bestwishes0203

  • 📷 封面壁纸:洛可可白wallpaper

在这里插入图片描述

这里写自定义目录标题

  • Spring Boot 中使用 Redis:从入门到实战
    • 一、添加 Redis 依赖
    • 二、配置 Redis 连接
      • application.properties 示例
      • application.yml 示例
    • 三、自定义 Redis 配置(可选)
      • Redis 配置类
    • 四、使用 `RedisTemplate` 进行基本操作
      • 1\. 增删改查操作
        • RedisService.java
      • 2\. 创建临时数据并自动删除
        • RedisService.java(临时数据)
      • 3\. 测试 Redis 功能
        • RedisController.java
    • 五、运行应用
    • 六、高级功能
      • 1\. 设置数据过期时间
        • 示例代码
      • 2\. 使用 Redis 的其他数据结构
        • 示例代码(使用列表)
    • 七、总结
    • 参考资料

Spring Boot 中使用 Redis:从入门到实战

在现代的 Spring Boot 应用程序中,Redis 是一种常用的高性能键值存储系统,广泛用于缓存、消息队列、分布式锁等场景。本文将详细介绍如何在 Spring Boot 项目中集成 Redis,并实现基本的增删改查操作、设置数据过期时间、创建临时数据等常用功能。

一、添加 Redis 依赖

在 Spring Boot 项目中,集成 Redis 非常简单。首先,你需要在项目的 pom.xml 文件中添加以下依赖:

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

这个依赖会自动引入 Spring Data Redis 的相关功能,并配置默认的 Redis 客户端连接。

如果你需要使用 Lettuce 作为 Redis 客户端(默认客户端),可以显式添加 Lettuce 依赖:

<dependency>
    <groupId>io.lettuce.core</groupId>
    <artifactId>lettuce-core</artifactId>
</dependency>

二、配置 Redis 连接

application.propertiesapplication.yml 文件中配置 Redis 的连接信息。

application.properties 示例

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=  # 如果设置了密码
spring.redis.database=0  # 数据库索引,默认为 0

application.yml 示例

spring:
  redis:
    host: localhost
    port: 6379
    password:  # 如果设置了密码
    database: 0  # 数据库索引,默认为 0

三、自定义 Redis 配置(可选)

如果你需要自定义 RedisTemplate 的序列化方式,可以创建一个配置类。默认情况下,Spring Data Redis 使用 JdkSerializationRedisSerializer 对象序列化器,这可能导致一些问题,例如存储的键值对是二进制格式,难以直接查看。因此,推荐使用 StringRedisSerializer

Redis 配置类

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.StringRedisSerializer;

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());
        return template;
    }
}

四、使用 RedisTemplate 进行基本操作

通过注入 RedisTemplateStringRedisTemplate,你可以轻松地操作 Redis。以下是一些常见的操作示例。

1. 增删改查操作

RedisService.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 存储数据
    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    // 存储数据并设置过期时间
    public void setWithExpire(String key, Object value, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    // 获取数据
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    // 删除数据
    public void delete(String key) {
        redisTemplate.delete(key);
    }
}

2. 创建临时数据并自动删除

通过设置过期时间,可以创建临时数据。当数据过期时,Redis 会自动删除它们。

RedisService.java(临时数据)
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 创建临时数据并设置过期时间
    public void createTemporaryData(String key, Object value, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }
}

3. 测试 Redis 功能

创建一个控制器来测试 Redis 功能。

RedisController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/redis")
public class RedisController {
    @Autowired
    private RedisService redisService;

    @PostMapping("/set")
    public String set(@RequestParam String key, @RequestParam String value) {
        redisService.set(key, value);
        return "Set successfully";
    }

    @GetMapping("/get")
    public Object get(@RequestParam String key) {
        return redisService.get(key);
    }

    @DeleteMapping("/delete")
    public String delete(@RequestParam String key) {
        redisService.delete(key);
        return "Deleted successfully";
    }

    @PostMapping("/setWithExpire")
    public String setWithExpire(@RequestParam String key, @RequestParam String value, @RequestParam long timeout) {
        redisService.setWithExpire(key, value, timeout, TimeUnit.SECONDS);
        return "Set with expire successfully";
    }
}

五、运行应用

确保 Redis 服务器正在运行,然后启动 Spring Boot 应用。你可以通过以下方式测试:

  • 存储数据:POST http://localhost:8080/api/redis/set?key=myKey&value=myValue
  • 获取数据:GET http://localhost:8080/api/redis/get?key=myKey
  • 删除数据:DELETE http://localhost:8080/api/redis/delete?key=myKey
  • 存储带过期时间的数据:POST http://localhost:8080/api/redis/setWithExpire?key=myKey&value=myValue&timeout=10

六、高级功能

1. 设置数据过期时间

在 Redis 中,可以通过设置过期时间(TTL)来让数据在指定时间后自动删除。这在实现缓存、会话管理等场景中非常有用。

示例代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 设置数据过期时间
    public void setWithExpire(String key, Object value, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }
}

2. 使用 Redis 的其他数据结构

Redis 不仅支持简单的键值对存储,还支持多种数据结构,如列表、集合、有序集合等。这些数据结构可以用于实现更复杂的业务逻辑。

示例代码(使用列表)
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RedisService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 向列表中添加元素
    public void addToList(String key, Object value) {
        redisTemplate.opsForList().rightPush(key, value);
    }

    // 从列表中获取所有元素
    public List<Object> getAllFromList(String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }
}

七、总结

在 Spring Boot 项目中集成 Redis 是非常简单的,通过 spring-boot-starter-data-redis 依赖,你可以快速实现 Redis 的基本操作和高级功能。本文介绍了如何添加 Redis 依赖、配置 Redis 连接、自定义 RedisTemplate、实现增删改查操作、设置数据过期时间以及使用 Redis 的其他数据结构。

希望这些内容能帮助你更好地理解和使用 Redis。如果你有任何问题或建议,欢迎在评论区留言。


参考资料

  • Spring Boot 官方文档
  • Spring Data Redis 官方文档
  • Redis 官方文档

如果对你有帮助,点赞👍、收藏💖、关注🔔是我更新的动力!👋🌟🚀

http://www.dtcms.com/a/112396.html

相关文章:

  • Websoft9分享:在数字化转型中选择开源软件可能遇到的难题
  • 神经网络能不能完全拟合y=x² ???
  • WinForm真入门(7)——Button控件详解
  • 京东运维面试题及参考答案
  • k8s进阶之路:本地集群环境搭建
  • 谷歌 Gemini 2.5 Pro 免费开放
  • 24、 Python Socket编程:从协议解析到多线程实战
  • 如何完整迁移 Git 仓库 ?
  • yum list查询时部分包查找不到流程分析
  • 54.大学生心理健康管理系统(基于springboot项目)
  • 有人DTU使用MQTT协议控制Modbus协议的下位机-含数据库
  • Redis分布式锁详解
  • AWS Langfuse AI用Bedrock模型使用完全教程
  • 【万字总结】前端全方位性能优化指南(八)——Webpack 6调优、模块联邦升级、Tree Shaking突破
  • 安卓离线畅玩的多款棋类单机游戏推荐
  • 【leetcode100】动态规划Java版本
  • Debezium日常分享系列之:Debezium 3.1.0.Final发布
  • 什么是量子计算?
  • 【代码艺廊】pyside6桌面应用范例:homemade-toolset
  • 如何实现浏览器中的报表打印
  • Pytorch使用GPU、CUDA安装步骤注意事项
  • Redis 中 Set(例如标签) 和 ZSet(例如排行榜) 的详细对比,涵盖定义、特性、命令、适用场景及总结表格
  • CSS 创建与使用学习笔记
  • 室内指路机器人是否支持环境监测功能?
  • 【数据分享】2002-2023中国湖泊水位变化数据集(免费获取)
  • 【数据结构】树的介绍
  • k8s的pod的概述和配置
  • Vue 未编译模板闪现现象解说
  • Spring Boot 与 TDengine 的深度集成实践(二)
  • 【力扣hot100题】(051)腐烂的橘子