1

I use Spring RestTemplate to consume other services in my local environment.

In production env for scalabilty i want to use a service registry like eureka and ribbon client.

I want to have a clean separation of my code from eureka and ribbon client so that i can run my services locally without the overhead of running a separate service for eureka , registering the services with eureka and also doing a lookup against eureka during orchestration.

I have used spring profile feature to separate out the code and configuration related local and production.

I am stuck at one point where I use RestTemplate to invoke other services.

I want to use the load balanced rest template for prod env and normal rest template for local service call.

I am having difficulty in injecting the type of RestTemplate based on my environment.

Can someone help me with the right way of injecting the RestTemplate so that my services can run locally as well as leverage service registry and ribbon client when running in Prod env without impacting the code.

Thanks, Sri

user6594900
  • 33
  • 1
  • 4

1 Answers1

0

Profiles

Use the @Profile annotation on your RestTemplate Bean.

Example:

@Configuration
public class Config {

    @Profile("local")
    @Bean
    public RestTemplate restTemplateLocal(){
        return new RestTemplate();
    }

    @Profile("production")
    @LoadBalanced
    @Bean
    public RestTemplate restTemplateProduction(){
        return new RestTemplate();
    }

}

Then you can Autowire this bean wherever you need and based on the active Profile, it will return either a normal or LoadBalanced RestTemplate.

@Autowired
private RestTemplate restTemplate;
Kyle Anderson
  • 6,801
  • 1
  • 29
  • 41
  • Thanks for your response. I have used your suggestion but i get the error message when lookup is done with loadbalanced resttemplate. I will share the code and error message. shortly. – user6594900 Jul 22 '16 at 09:00
  • @user6594900 Okay. Make sure that when you run the application, you specify an active profile (e.g. local, production) or else no RestTemplate bean will be instantiated. – Kyle Anderson Jul 22 '16 at 14:48
  • @user6594900 To enable a profile try: java -Dspring.profiles.active=local -jar app.jar – Kyle Anderson Jul 22 '16 at 14:49