如何在Spring Boot中使用RedisTemplate
warning:
这篇文章距离上次修改已过432天,其中的内容可能已经有所变动。
在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配置,例如主机名、端口和密码(如果有的话)。
评论已关闭