2016-12-19 8 views
0

Я два microservices,эврика UnknownHostException в открытии службы

  1. эврика-клиент-1, работающие на локальном хосте: 8081
  2. эврика-клиент-2, работающие на локальном хосте: 8082

Оба это DiscoveryClients, зарегистрированные с «eureka-server», работающие на localhost: 8761.

В нижеприведенном фрагменте кода я пытаюсь вызвать eureka-client-2 из eureka-client-1. Вместо вызова http://localhost:8082, я хочу позвонить http://eureka-client-2, но это вызывает java.net.UnknownHostException во время обнаружения службы Eureka.

После поиска я обнаружил, что мне нужно использовать «Brixton», чтобы это сделать.

Есть ли способ сделать это с помощью Camden.SR3?

Просьба предложить.

@Component 
public class HystrixDemoService { 

    @Bean 
    @LoadBalanced 
    public RestTemplate restTemplate() { 
     return new RestTemplate(); 
    } 

    @HystrixCommand(fallbackMethod = "getFallbackCustomerName") 
    public String getCustomerName() { 
     RestTemplate restTemplate = new RestTemplate(); 
     URI uri = URI.create("http://eureka-client-2");  // fails here 
     return restTemplate.getForObject(uri, String.class); 
    } 

    public String getFallbackCustomerName() { 
     System.out.println("coming inside fallback method"); 
     return "Resillient Customer"; 
    } 
} 

pom.xml

<?xml version="1.0" encoding="UTF-8"?> 
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 

    <groupId>com.example</groupId> 
    <artifactId>demo-pranay-eureka-client1</artifactId> 
    <version>0.0.1-SNAPSHOT</version> 
    <packaging>jar</packaging> 

    <name>demo-pranay-eureka-client1</name> 
    <description>Demo project for Spring Boot</description> 

    <parent> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-parent</artifactId> 
     <version>1.4.2.RELEASE</version> 
     <relativePath/> <!-- lookup parent from repository --> 
    </parent> 

    <properties> 
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
     <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 
     <java.version>1.8</java.version> 
    </properties> 

    <dependencies> 
     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-actuator</artifactId> 
     </dependency> 
     <dependency> 
      <groupId>org.springframework.cloud</groupId> 
      <artifactId>spring-cloud-starter-eureka</artifactId> 
     </dependency> 
     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-web</artifactId> 
     </dependency> 
     <dependency> 
      <groupId>org.springframework.cloud</groupId> 
      <artifactId>spring-cloud-starter-hystrix</artifactId> 
     </dependency> 
     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-test</artifactId> 
      <scope>test</scope> 
     </dependency> 
    </dependencies> 

    <dependencyManagement> 
     <dependencies> 
      <dependency> 
       <groupId>org.springframework.cloud</groupId> 
       <artifactId>spring-cloud-dependencies</artifactId> 
       <version>Camden.SR3</version> 
       <type>pom</type> 
       <scope>import</scope> 
      </dependency> 
     </dependencies> 
    </dependencyManagement> 

    <build> 
     <plugins> 
      <plugin> 
       <groupId>org.springframework.boot</groupId> 
       <artifactId>spring-boot-maven-plugin</artifactId> 
      </plugin> 
     </plugins> 
    </build> 


</project> 

application.properties для клиента 1, аналогичные для клиента 2 (только изменить в названии т.е. эврика-клиент-2)

spring.application.name=eureka-client-1 
server.port=8081 
eureka: 
    client: 
    registerWithEureka: true 
    serviceUrl: 
     defaultZone: http://localhost:8761/eureka/ 
    instance: 
    leaseRenewalIntervalInSeconds: 10 
    statusPageUrlPath: /info 
    healthCheckUrlPath: /health 

application.properties для эврика-сервера

spring.application.name=eureka-service 
server.port=8761 
eureka: 
    client: 
    registerWithEureka: false 
    serviceUrl: 
     defaultZone: http://localhost:8761/eureka/ 
    instance: 
    leaseRenewalIntervalInSeconds: 10 
    statusPageUrlPath: /info 
    healthCheckUrlPath: /health 
+0

Не могли бы вы показать ваши конфигурационные файлы (application.yml, application.properties , bootstrap.yml, ...) – ootero

+0

привет @ootero, я обновил вопрос. файл application.properties. – prranay

+0

Когда вы открываете сервер 'Eureka' по адресу: http: // localhost: 8761/eureka /, вы можете видеть зарегистрированные eureka-client-1 и eureka-client-1? Я думаю, что вам не хватает конфигурации «Ribbon» в eureka-client-1 – ootero

ответ

1

Изменения ниже работали для меня.

@SpringBootApplication 
public class DemoPranayEurekaClient1Application { 
    public static void main(String[] args) { 
     SpringApplication.run(DemoPranayEurekaClient1Application.class, args); 
    } 
} 

@EnableDiscoveryClient 
@EnableCircuitBreaker 
@RestController 
class HystrixDemoApplication { 
    @Autowired 
    HystrixDemoService hystrixDemoService; 

    @Bean 
    @LoadBalanced 
    public RestTemplate restTemplate() { 
     return new RestTemplate(); 
    } 

    @RequestMapping("/") 
    public String name() { 
     String str = hystrixDemoService.getCustomerName(); 
     return "I'm A talking to "+str; 
    } 

} 

Ниже приведена строка кода, используемая для выбора экземпляра eureka-client-2 ...

Экземпляр ServiceInstance = loadBalancer.choose ("eureka-client-2");

@Component 
public class HystrixDemoService { 

    @Autowired 
    private LoadBalancerClient loadBalancer; 

    @HystrixCommand(fallbackMethod = "getFallbackCustomerName") 
    public String getCustomerName() { 
     RestTemplate restTemplate = new RestTemplate(); 
     ServiceInstance instance = loadBalancer.choose("eureka-client-2"); 
     URI uri = instance.getUri(); 
     return restTemplate.getForObject(uri, String.class); 
    } 

    public String getFallbackCustomerName() { 
     System.out.println("coming inside fallback method"); 
     return "Resillient Customer"; 
    } 
} 
1

Как я уже говорил, я считаю, что вы можете отсутствовать в конфигурации в eureka-client-1.

Во-первых, я хотел бы перейти:

@Bean 
@LoadBalanced 
public RestTemplate restTemplate() { 
    return new RestTemplate(); 
} 

к классу конфигурации.

Добавить Ribbon конфигурации application.yml, что-то вроде:

the-eureka-client-2: 
    ribbon: 
    # Eureka vipAddress of the target service 
    DeploymentContextBasedVipAddresses: eureka-client-2 

    #listOfServers: localhost:${SERVER.PORT} 
    NIWSServerListClassName: com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList 

    # Interval to refresh the server list from the source (ms) 
    ServerListRefreshInterval: 30000 

Вводит restTemplate в HystrixDemoService классе вместо инстанцирования новой для каждого запроса. RestTemplate потокобезопасно:

@Component 
public class HystrixDemoService { 

    @Autowired 
    public RestTemplate restTemplate; 
... 
    @HystrixCommand(fallbackMethod = "getFallbackCustomerName") 
    public String getCustomerName() { 
     URI uri = URI.create("http://eureka-client-2"); 
     return this.restTemplate.getForObject(uri, String.class); 
    } 

где the-eureka-client-2 является ключом, который отображает на зарегистрированную службу с именем: eureka-client-2

Я писал о Microservices Registration and Discovery using Spring Cloud Eureka, Ribbon and Feign, который также включает в себя исходный код сервера Discovery и двух клиентов, разработанных с использованием Jersey 1 и Spring MVC.