Using EurekaClient

Let's create the HomeController class and auto-wire com.netflix.discovery.EurekaClient:

package com.dineshonjava.eurekaclient; 
 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.web.bind.annotation.GetMapping; 
import org.springframework.web.bind.annotation.Controller; 
 
import com.netflix.appinfo.InstanceInfo; 
import com.netflix.discovery.EurekaClient; 
import com.netflix.discovery.shared.Application; 
 
@Controller 
public class HomeController { 
    
   @Autowired 
   private EurekaClient eurekaClient; 
    
   public String serviceUrl() { 
       Application application = eurekaClient.getApplication("spring-cloud-eureka-client"); 
       InstanceInfo instanceInfo = application.getInstances().get(0); 
       String hostname = instanceInfo.getHostName(); 
       int port = instanceInfo.getPort(); 
       // we can find many information related to the instance 
       return instanceInfo.getHomePageUrl(); 
   } 
    
   ... 
} 

As you can see, we have put EurekaClient into our controller with which we could receive service information by service name as an Application object.

Don't use EurekaClient in the @PostConstruct or @Scheduled methods. Because it is initialized in SmartLifecycle (with phase=0), the earliest you can rely on it being available is in another SmartLifecycle with a higher phase.

By default, EurekaClient uses Jersey for HTTP communication. But you can avoid using it by excluding Jersey from the Maven dependencies. Spring Cloud will auto-configure the org.springframework.web.client.RestTemplate template of the Spring. Spring Cloud provides alternatives to the native Netflix EurekaClient. So, if you don't want to use the native Netflix EurekaClient, Spring cloud supports Feign and also Spring RestTemplate. They use logical Eureka service identifiers instead of physical URLs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.93.20