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

Spring Boot整合Redis

前言

Redis是一种高性能的键值对存储系统,广泛应用于缓存、会话管理、消息队列等场景。Spring Boot作为一个简化Spring应用开发的框架,与Redis的整合能够有效提升应用的性能和响应速度。本文将详细介绍如何在Spring Boot项目中整合Redis。

环境准备

在开始整合之前,确保已经安装并运行了Redis服务器。可以通过以下命令检查Redis服务器是否运行:

redis-server
​

如果Redis没有安装,可以参考官方文档进行安装。

创建Spring Boot项目

首先,创建一个新的Spring Boot项目。在项目的 pom.xml文件中添加Spring Boot和Redis的依赖:

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

配置Redis

在 src/main/resources目录下的 application.properties文件中添加Redis的配置:

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password= # 如果有密码,填入对应的密码
​

创建Redis配置类

为了更灵活地管理Redis的连接和操作,可以创建一个配置类 RedisConfig

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.core.StringRedisTemplate;@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(redisConnectionFactory);return template;}@Beanpublic StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {return new StringRedisTemplate(redisConnectionFactory);}
}
​

使用RedisTemplate操作Redis

在Spring Boot中,可以使用 RedisTemplate或 StringRedisTemplate来操作Redis数据。以下是一个简单的示例,展示如何使用 RedisTemplate进行基本的CRUD操作。

创建服务类

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 {@Autowiredprivate RedisTemplate<String, Object> redisTemplate;public void setValue(String key, Object value) {redisTemplate.opsForValue().set(key, value);}public Object getValue(String key) {return redisTemplate.opsForValue().get(key);}public void deleteValue(String key) {redisTemplate.delete(key);}public void setValueWithExpiration(String key, Object value, long timeout, TimeUnit unit) {redisTemplate.opsForValue().set(key, value, timeout, unit);}
}
​

创建控制器

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/redis")
public class RedisController {@Autowiredprivate RedisService redisService;@PostMapping("/set")public void setValue(@RequestParam String key, @RequestParam String value) {redisService.setValue(key, value);}@GetMapping("/get")public String getValue(@RequestParam String key) {return (String) redisService.getValue(key);}@DeleteMapping("/delete")public void deleteValue(@RequestParam String key) {redisService.deleteValue(key);}@PostMapping("/setWithExpiration")public void setValueWithExpiration(@RequestParam String key, @RequestParam String value,@RequestParam long timeout) {redisService.setValueWithExpiration(key, value, timeout, TimeUnit.SECONDS);}
}
​

启动应用

确保主类位于包的顶层,并包含 @SpringBootApplication注解:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class RedisApplication {public static void main(String[] args) {SpringApplication.run(RedisApplication.class, args);}
}
​

启动应用程序,并通过以下示例测试Redis的操作:

  • 设置值:

    curl -X POST "http://localhost:8080/redis/set?key=testKey&value=testValue"
    ​
    
  • 获取值:

    curl "http://localhost:8080/redis/get?key=testKey"
    ​
    
  • 删除值:

    curl -X DELETE "http://localhost:8080/redis/delete?key=testKey"
    ​
    
  • 设置具有过期时间的值:

    curl -X POST "http://localhost:8080/redis/setWithExpiration?key=testKey&value=testValue&timeout=60"
http://www.xdnf.cn/news/576109.html

相关文章:

  • RestTemplate 发送的字段第二个大写字母变成小写的问题探究
  • 9-码蹄集600题基础python篇
  • leetcode 螺旋矩阵 java
  • 5-码蹄集600题基础python篇
  • 如何设计智慧工地系统的数据库?
  • 系统程序变更管理:确保IT环境稳定性和安全性的关键
  • Entity-Relationship Model(实体-关系模型)
  • FlashAttention:传统自注意力( Self-Attention)优化加速实现
  • 用户刷题记录日历——签到表功能实现
  • 基于 Guns v5.1 框架的分页教程
  • SseEmitter是什么
  • 卷积神经网络基础(十)
  • chrono类 根据duration 类的周期类型得到对应的周期名称
  • 预警功能深度测评:如何用系统降低设备突发故障率?
  • JavaScript常用事件
  • 第P10周:Pytorch实现车牌识别
  • 如何解决测试覆盖率与迭代速度的冲突问题?
  • 手搓四人麻将程序
  • 正大模型视角下的高频交易因子构建策略研究
  • 视频监控管理平台EasyCVR工业与公共安全监控:监控中心与防爆系统如何集成?
  • 【免杀】C2免杀技术(八)APC注入
  • 数字化转型到底是什么?如何更好的理解数字化转型
  • NOSQL之Redis群集部署
  • 基于Browser Use + Playwright 实现AI Agent操作Web UI自动化
  • 运行时runtime是什么?(程序在运行过程中所依赖的环境、资源管理机制以及动态行为的总和)(包括内存分配、异常处理、线程调度、类型检查、资源访问等)
  • ip地址冲突说明什么问题?ip地址冲突影响网速吗
  • torch.matmul() VS torch.einsum()
  • 2025上半年软考准考证打印入口已开放!
  • ubuntu24.04+RTX5090D 显卡驱动安装
  • 支持向量存储:PostgresSQL及pgvector扩展详细安装步骤!老工程接入RAG功能必备!