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 {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        return new StringRedisTemplate(redisConnectionFactory);
    }
}
​

使用RedisTemplate操作Redis

在Spring Boot中,可以使用 RedisTemplateStringRedisTemplate来操作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 {

    @Autowired
    private 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 {

    @Autowired
    private 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"
相关推荐
风流倜傥唐伯虎10 小时前
Spring Boot Jar包生产级启停脚本
java·运维·spring boot
fuquxiaoguang10 小时前
深入浅出:使用MDC构建SpringBoot全链路请求追踪系统
java·spring boot·后端·调用链分析
毕设源码_廖学姐11 小时前
计算机毕业设计springboot招聘系统网站 基于SpringBoot的在线人才对接平台 SpringBoot驱动的智能求职与招聘服务网
spring boot·后端·课程设计
顾北1211 小时前
MCP服务端开发:图片搜索助力旅游计划
java·spring boot·dubbo
昀贝12 小时前
IDEA启动SpringBoot项目时报错:命令行过长
java·spring boot·intellij-idea
indexsunny13 小时前
互联网大厂Java面试实战:Spring Boot微服务在电商场景中的应用与挑战
java·spring boot·redis·微服务·kafka·spring security·电商
Coder_Boy_14 小时前
基于SpringAI的在线考试系统-相关技术栈(分布式场景下事件机制)
java·spring boot·分布式·ddd
韩立学长16 小时前
基于Springboot泉州旅游攻略平台d5h5zz02(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·旅游
摇滚侠16 小时前
在 SpringBoot 项目中,开发工具使用 IDEA,.idea 目录下的文件需要提交吗
java·spring boot·intellij-idea
打工的小王18 小时前
Spring Boot(三)Spring Boot整合SpringMVC
java·spring boot·后端