springboot怎么整合redis
时间: 2023-12-03 13:39:28 浏览: 83
微服务SpringBoot整合Redis基于Redis的Stream消息队列实现异步秒杀下单
5星 · 资源好评率100%
以下是使用Spring Boot整合Redis的步骤:
1.在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2.在application.properties文件中添加以下配置:
```properties
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器连接密码(默认为空)
spring.redis.password=
```
3.创建Redis配置类,用于配置RedisTemplate和StringRedisTemplate:
```java
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
stringRedisTemplate.setConnectionFactory(redisConnectionFactory);
return stringRedisTemplate;
}
}
```
4.在需要使用Redis的类中注入RedisTemplate或StringRedisTemplate,并使用它们进行操作:
```java
@Service
public class UserService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public User getUserById(Long id) {
String key = "user_" + id;
User user = (User) redisTemplate.opsForValue().get(key);
if (user == null) {
user = getUserFromDatabase(id);
redisTemplate.opsForValue().set(key, user);
}
return user;
}
private User getUserFromDatabase(Long id) {
// 从数据库中获取用户信息
}
}
```
阅读全文