我正在使用java8和Spring Cloud在微服务架构中开发一个系统。我实现了一个post控制器,它接收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 Gateway路径的端点。
检索此URI的最佳实践是什么?
发布于 2019-06-12 13:07:47
所以,我找到了一个解决方案,我只是不知道这是不是最好的做法。我的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();
}
https://stackoverflow.com/questions/56553011
复制