springboot整合redis步骤
时间: 2023-07-06 22:40:36 浏览: 116
下面是Spring Boot整合Redis的步骤:
1. 引入Redis依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2. 配置Redis连接信息
在`application.properties`或`application.yml`中添加Redis连接信息:
```
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
```
3. 配置RedisTemplate
在配置类中创建RedisTemplate实例,并配置其序列化方式:
```
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
}
```
4. 使用RedisTemplate操作Redis
在需要使用Redis的地方注入RedisTemplate,并调用其相应方法即可:
```
@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的基本步骤。
阅读全文
相关推荐










