我正在后台开发一个带有spring boot的模块,我需要通过GCP内存存储使用Redis。我一直在论坛上搜索;"社会文件";关于内存存储,但我不知道如何用我的springboot应用程序连接到内存存储。
我找到了一个谷歌代码实验室,但他们使用计算引擎虚拟机安装spring-boot,然后从内存存储中保存和检索信息。所以我试着在我当地的春季靴子里这样做,但没有成功,因为出现了一个错误:
无法连接到Redis;嵌套异常为io.lettuce.core.RedisConnectionException:无法连接到10.1.3.4
我前面提到的codelab说,您只需要将这一行添加到您的应用程序中。properties:
spring.redis.host=10.1.3.4
以及main类中的注释@EnableCaching和controller方法中的@Cachable注释,您尝试在其中使用redis。
方法看起来是这样的:
@RequestMapping("/hello/{name}")
@Cacheable("hello")
public String hello(@PathVariable String name) throws InterruptedException {
Thread.sleep(5000);
return "Hello " + name;
}
我不知道还能做什么。注意,我对redis和内存存储这个话题还很陌生。
有人能给我一些指导吗?
提前感谢
代码实验室网址:https://codelabs.developers.google.com/codelabs/cloud-spring-cache-memorystore#0
请参阅有关如何设置Memorystore Redis实例的文档。
文档中包括如何从不同的计算环境连接和测试Memorystore实例。
还有一个关于SpringBoot如何使用Redis缓存annonations的分步指南。
- 如果您使用Maven进行项目设置,请在pom.xml中添加Spring Data Redis启动器
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 在application.properties文件中添加此配置:
spring.redis.host=<MEMORYSTORE_REDIS_IP>
# Configure default TTL, e.g., 10 minutes
spring.cache.redis.time-to-live=600000
- 使用@EnableCaching注释显式启用缓存功能:
@SpringBootApplication
@EnableCaching
class DemoApplication {
...
}
- 使用Redis配置Spring Boot并启用缓存后,就可以使用@Cacheable注释来缓存返回值
@Service
class OrderService {
private final OrderRepository orderRepository;
public OrderService(OrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
@Cacheable("order")
public Order getOrder(Long id) {
orderRepository.findById(id);
}
}