Cacheable储存于redis的写法
在使用@Cacheable注解时,需要使用Spring Data Redis来实现储存于Redis中。以下是@Cacheable储存于Redis的写法:
- 首先,需要在Spring Boot项目中添加Redis依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 然后,在application.properties中配置Redis连接信息:
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=redispassword
- 接着,在需要缓存的方法上添加@Cacheable注解,指定缓存key和缓存时间:
@Cacheable(value = "myCache", key = "#id", cacheManager = "myCacheManager", unless = "#result == null", expire = 3600)
public User getUserById(Long id) {
// 从数据库中获取用户信息
User user = userRepository.findById(id).orElse(null);
return user;
}
- 最后,需要配置一个CacheManager来管理缓存:
@Configuration
@EnableCaching
public class RedisCacheConfig {
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Bean
public CacheManager myCacheManager() {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(3600))
.disableCachingNullValues();
return RedisCacheManager.builder(redisConnectionFactory)
.cacheDefaults(redisCacheConfiguration)
.build();
}
}
通过以上步骤,@Cacheable注解就可以将方法的返回值缓存到Redis中了。当再次调用该方法时,如果缓存中存在对应的缓存key,则直接返回缓存中的数据,而不是再次执行该方法。如果缓存中不存在对应的缓存key,则执行该方法并将返回值缓存到Redis中。
原文地址: https://www.cveoy.top/t/topic/bqcq 著作权归作者所有。请勿转载和采集!