在 Spring Boot 中整合 Redis 可以通过以下步骤来实现:
1、添加 Redis 依赖:在你的项目的 pom.xml 文件中添加 Redis 相关的依赖。可以使用 Spring Boot 提供的 spring-boot-starter-data-redis starter,它会自动配置 Redis 相关的依赖和bean。
xml
<dependencies>
<!-- 其他依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
2、配置 Redis 连接:在 application.yml 配置文件中添加 Redis 连接参数。示例配置如下:
server:
port: 10086
spring:
redis:
host: localhost
port: 6379
password:
database: 0
3、使用 RedisTemplate 进行操作:通过注入 RedisTemplate,你可以在代码中使用它来执行对 Redis 的操作。示例代码如下:
package com.yunya.springboot_redis.controller;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("redis")
public class RedisController {
private final RedisTemplate redisTemplate;
public RedisController(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
@GetMapping("save")
public String save(String key, String value) {
System.out.println("begin");
String redis_val = (String) redisTemplate.opsForValue().get(key);
System.out.println("redis_val:"+redis_val);
redisTemplate.opsForValue().set(key, value);
System.out.println("redisController save() working");
return "success";
}
}
4、打开浏览器输入网址:http://localhost:10086/redis/save?key=springredis&value=two,返回结果如下:
通过以上步骤,你就可以在 Spring Boot 中成功地整合 Redis,并使用 RedisTemplate 来执行相应的操作。当然,这只是一个简单的示例,你还可以根据具体需求来使用 Redis 提供的其他功能,如 Hash、List、Set 等数据结构的操作。