springboot整合redis 增删改查实例
时间: 2023-08-12 12:04:50 浏览: 99
好的,下面是一个简单的Spring Boot整合Redis的增删改查实例:
1. 添加Redis依赖
在pom.xml中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2. 配置Redis连接
在application.properties中添加以下配置:
```properties
# Redis连接配置
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
```
3. 编写Redis操作类
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class RedisDao {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void set(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
public void delete(String key) {
redisTemplate.delete(key);
}
}
```
4. 编写Controller
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/redis")
public class RedisController {
@Autowired
private RedisDao redisDao;
@PostMapping("/set")
public void set(@RequestParam String key, @RequestParam String value) {
redisDao.set(key, value);
}
@GetMapping("/get")
public Object get(@RequestParam String key) {
return redisDao.get(key);
}
@DeleteMapping("/delete")
public void delete(@RequestParam String key) {
redisDao.delete(key);
}
}
```
5. 测试
启动应用后,可以通过以下方式测试:
- 设置值:POST http://localhost:8080/redis/set?key=test&value=hello
- 获取值:GET http://localhost:8080/redis/get?key=test
- 删除值:DELETE http://localhost:8080/redis/delete?key=test
以上就是一个简单的Spring Boot整合Redis的增删改查实例。
阅读全文