如何在Spring Boot中使用RedisTemplate
在Spring Boot中使用RedisTemplate
,首先需要在项目中添加Spring Data Redis依赖。以下是一个基本的例子:
- 添加依赖到你的
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 配置
RedisTemplate
:
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
return template;
}
}
- 使用
RedisTemplate
:
@Service
public class RedisService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void setValue(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Object getValue(String key) {
return redisTemplate.opsForValue().get(key);
}
}
确保你的application.properties
或application.yml
文件中包含正确的Redis配置,例如主机名、端口和密码(如果有的话)。
评论已关闭