Spring Boot 使用 Redis
warning:
这篇文章距离上次修改已过433天,其中的内容可能已经有所变动。
在Spring Boot中使用Redis,你可以使用spring-boot-starter-data-redis依赖。以下是一个简单的例子:
- 添加依赖到你的
pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>- 在
application.properties或application.yml中配置Redis连接:
# application.properties
spring.redis.host=localhost
spring.redis.port=6379- 使用
RedisTemplate或StringRedisTemplate操作Redis:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
@RestController
public class RedisController {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@GetMapping("/set")
public String setKey(@RequestParam String key, @RequestParam Object value) {
redisTemplate.opsForValue().set(key, value);
return "success";
}
@GetMapping("/get")
public Object getKey(@RequestParam String key) {
return redisTemplate.opsForValue().get(key);
}
}这个例子中,我们创建了一个简单的RESTful控制器,提供了设置和获取Redis缓存数据的接口。使用RedisTemplate可以操作不同类型的数据。
评论已关闭