0

I'm developing a system in a microservices architecture using java8 and Spring Cloud. I implemented a post rest controller that receives an object in json and then saves it in the database. The problem is; how do I get the URI containing the API Gateway of the just saved object so I can return it on the created responde body?

Like, when I use URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(savedProfile.getId()).toUri(); I get http://Boss.mshome.net:8081/profile/1 instead of localhost:8765/nukr-profile-service/profile/1 which is the endpoint with the API Gateway's path.

What's the best practice to retrieve this URI?

2
  • Why do you need to return api gateway url at all? Isn't it known explicitly? Commented Jun 13, 2019 at 7:35
  • It is. The thing is, I wanted to load it from eureka naming server, in case it changed port or server. So I decided to go with the solution I posted as an answer here. This way, even if the Gateway's url changes, it will not be a problem, since I'm loading it from Eureka naming server. Commented Jun 14, 2019 at 18:52

1 Answer 1

0

So, I came to a solution I just don't know if it's best practice or not. My post method ended up being like:

@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(); } 
Sign up to request clarification or add additional context in comments.

1 Comment

I've accepted my own answer, since it worked. But I'm sure there may be a more elegant way to do it -maybe using a config server?-. So if you know a better way to do it, please answer and I'll consider and maybe accept your answer!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.