Redis 是一个高性能的键值存储系统,它可以用来存储各种数据,包括字符串、列表、集合、哈希表等。Spring Boot 提供了对 Redis 的支持,可以很方便地在 Spring Boot 应用程序中使用 Redis。
以下是使用 Spring Boot 使用 Redis 实现缓存的步骤:
- 在 pom.xml 文件中添加 Spring Boot 对 Redis 的依赖。
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 在 application.yml 文件中配置 Redis 的连接信息。
redis:
host: localhost
port: 6379
- 创建一个 RedisTemplate 对象。
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(new JedisConnectionFactory());
return redisTemplate;
}
- 在需要缓存数据的方法中使用 RedisTemplate 对象。
@GetMapping("/get")
public String get() {
return redisTemplate.opsForValue().get("key");
}
@PostMapping("/put")
public void put(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
这样,我们就使用 Spring Boot 使用 Redis 实现了缓存。