redis在springboot配置代码
时间: 2023-12-03 10:04:04 浏览: 73
在Spring Boot应用中使用Redis需要以下步骤:
1. 添加Redis的依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2. 配置Redis连接信息
在application.yml或application.properties文件中添加Redis的连接信息:
```
spring.redis.host=127.0.0.1
spring.redis.port=6379
```
3. 创建RedisTemplate对象
可以通过以下方式创建RedisTemplate对象:
```
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
```
4. 使用RedisTemplate操作Redis
通过RedisTemplate对象可以操作Redis,例如:
```
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void set(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
```
这样就可以在Spring Boot应用中使用Redis了。
阅读全文
相关推荐


















