Home > Net >  When use RestTemplate to call multiple services, single instance for all or one instance per service
When use RestTemplate to call multiple services, single instance for all or one instance per service

Time:09-29

We need to call several service in our application by RestTemplate. like this:

  • abc.test/api_one/
  • abc.test/api_one/
  • egf.test/api_alpha/
  • egf.test/api_beta/
  • xyz.test/api_a/

There are three opinion in team.

  1. Single instance for all of them.
  2. Instance per Endpoints (abc.test, egf.test, xyz.test)
  3. Instance per APIs

I think the answer is dependent on situation, so question is how to determine ? What kinds of element should we based on ?

CodePudding user response:

RestTemplate is thread-safe. It makes sense to create as many instances as many different configurations (for example different message converters) you have.

CodePudding user response:

You can use single api is enough using with @PathVariable

@PathVariable is a Spring annotation which indicates that a method parameter should be bound to a URI template variable.

@RequestMapping(path="/{name}}")

name - name of the path variable to bind to request

Dependents on request your pathvaraible name is aliased with api_alpha,api_beta....like egf.test/api_aplha

Single request if you wants to invoke all of above

@RequestMapping(path="/{param1}/{param2}")

In your case @RequestMapping(path="egf.test/{name1}/{name2}")and request url like /egf.test/api_aplha/api_beta

Inside your controller class like this

@RestController
public class MyController {
@RequestMapping(path="/{name}/{name2}")
public <returnType> getTestInvoke(@PathVariable("name") String name, 
        @PathVariable("name2") String name2) {
  ...
    return <returntype>;
 }
}
  • Related