springboot中使用redis缓存
时间: 2023-10-24 11:58:17 浏览: 127
在Spring Boot中使用Redis缓存,你需要进行以下几个步骤:
1. 添加依赖:在pom.xml文件中添加Spring Data Redis依赖。
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
```
2. 配置Redis连接信息:在application.properties或application.yml文件中配置Redis连接信息,如下所示:
```yaml
spring.redis.host=your_redis_host
spring.redis.port=your_redis_port
spring.redis.password=your_redis_password (如果有密码的话)
```
3. 创建Redis配置类:创建一个Redis配置类,用于配置RedisTemplate和CacheManager。可以参考下面的示例:
```java
@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
// 设置key和value的序列化器
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.disableCachingNullValues()
.entryTtl(Duration.ofMinutes(10)) // 设置缓存过期时间为10分钟
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(cacheConfiguration)
.build();
}
}
```
4. 使用缓存注解:在需要使用缓存的方法上添加缓存注解,如@Cacheable、@CachePut、@CacheEvict等。例如:
```java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Cacheable(value = "users", key = "#id")
public User getUserById(Integer id) {
return userRepository.findById(id).orElse(null);
}
@CachePut(value = "users", key = "#user.id")
public User saveUser(User user) {
return userRepository.save(user);
}
@CacheEvict(value = "users", key = "#id")
public void deleteUser(Integer id) {
userRepository.deleteById(id);
}
}
```
以上就是在Spring Boot中使用Redis缓存的基本步骤。你可以根据实际需求进行配置和使用不同的缓存注解。
阅读全文