springboot整合Redis怎么在idea中实现
时间: 2023-06-10 19:03:04 浏览: 160
您好,关于您的问题,可以按照以下步骤来实现springboot整合Redis在idea中的操作:
1. 在pom.xml文件中添加Redis依赖
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2. 在application.properties中添加Redis配置
```
spring.redis.host=127.0.0.1
spring.redis.port=6379
```
3. 创建一个Redis配置类
```
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
Jackson2JsonRedisSerializer<Object> serializer =
new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(objectMapper);
// 设置value的序列化规则和 key的序列化规则
redisTemplate.setValueSerializer(serializer);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
```
4. 在需要使用Redis的地方注入RedisTemplate,然后即可使用Redis的API进行操作。
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Override
public User getUserById(Long id) {
String key = "user_" + id;
User user = (User) redisTemplate.opsForValue().get(key);
if (user == null) {
user = userRepository.selectById(id);
if (user != null) {
redisTemplate.opsForValue().set(key, user, 1, TimeUnit.MINUTES); // 缓存一分钟
}
}
return user;
}
}
```
希望以上步骤可以帮到您,如果还有其他问题,请随时提出。
阅读全文