Spring Boot 接入 Redis
warning:
这篇文章距离上次修改已过418天,其中的内容可能已经有所变动。
要在Spring Boot中接入Redis,你需要做以下几步:
- 添加Spring Data Redis和Jedis依赖到你的
pom.xml文件中。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>- 在
application.properties或application.yml中配置Redis连接信息。
# application.properties
spring.redis.host=localhost
spring.redis.port=6379- 使用Spring提供的
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);
}
}以上代码展示了如何在Spring Boot应用中通过RedisTemplate来简单地进行Redis的键值对的设置和获取操作。
评论已关闭