【问题标题】:How to retrieve the API Gateway URI upon post如何在发布时检索 API Gateway URI
【发布时间】:2019-10-26 10:12:44
【问题描述】:

我正在使用 java8 和 Spring Cloud 在微服务架构中开发一个系统。我实现了一个 post rest 控制器,它接收 json 中的对象,然后将其保存在数据库中。问题是;如何获取包含刚刚保存的对象的 API 网关的 URI,以便可以在创建的响应主体上返回它?

比如,当我使用 URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(savedProfile.getId()).toUri(); 时,我得到的是http://Boss.mshome.net:8081/profile/1 而不是localhost:8765/nukr-profile-service/profile/1,后者是API 网关路径的端点。

检索此 URI 的最佳做法是什么?

【问题讨论】:

  • 为什么需要返回api网关url?不是明确知道的吗?
  • 是的。问题是,我想从 eureka 命名服务器加载它,以防它更改端口或服务器。所以我决定使用我在这里发布的解决方案作为答案。这样即使Gateway的url改变了也不会有问题,因为我是从Eureka命名服务器加载的。

标签: uri spring-cloud netflix-eureka api-gateway


【解决方案1】:

所以,我找到了一个我只是不知道它是否是最佳实践的解决方案。 我的 post 方法最终是这样的:

@PostMapping("/profile")
    public ResponseEntity<Object> createProfile(@Valid @RequestBody Profile profile) {
        UriComponents requestComponents = ServletUriComponentsBuilder.fromCurrentRequest().path("").build();
        InstanceInfo gatewayService = this.eurekaClient.getNextServerFromEureka(NUKR_API_GATEWAY_SERVICE, false);
        Profile savedProfile = this.profileRepository.save(profile);

        String uriStr = requestComponents.getScheme() + "://" + gatewayService.getIPAddr() + ":" + gatewayService.getPort() + "/" + this.profileServiceName +
                requestComponents.getPath() + "/" + savedProfile.getId();

        return ResponseEntity.created(URI.create(uriStr)).build();
    }

【讨论】:

  • 我已经接受了我自己的答案,因为它有效。但我敢肯定,可能有更优雅的方式来做到这一点——也许使用配置服务器?-。因此,如果您知道更好的方法,请回答,我会考虑并可能接受您的回答!
猜你喜欢
  • 2017-06-26
  • 2018-12-05
  • 2020-11-26
  • 2021-01-29
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 2019-11-25
  • 1970-01-01
相关资源
最近更新 更多