Importante

Você está vendo a versão anterior da nova experiência da Alura que estamos preparando para você. Em breve, ela ganha uma identidade visual novinha totalmente pensada em potencializar seus estudos!

10
respostas

Problema ao fazer Service Discovery com Eureka mapeando a url do fornecedor

Fiz o registros das duas aplicações no eureka:

<applications>
    <versions__delta>1</versions__delta>
    <apps__hashcode>UP_2_</apps__hashcode>
    <application>
        <name>LOJA</name>
        <instance>
            <instanceId>10.13.23.69:loja:9080</instanceId>
            <hostName>10.13.23.69</hostName>
            <app>LOJA</app>
            <ipAddr>10.13.23.69</ipAddr>
            <status>UP</status>
            <overriddenstatus>UNKNOWN</overriddenstatus>
            <port enabled="true">9080</port>
            <securePort enabled="false">443</securePort>
            <countryId>1</countryId>
            <dataCenterInfo class="com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo">
                <name>MyOwn</name>
            </dataCenterInfo>
            <leaseInfo>
                <renewalIntervalInSecs>30</renewalIntervalInSecs>
                <durationInSecs>90</durationInSecs>
                <registrationTimestamp>1574766976271</registrationTimestamp>
                <lastRenewalTimestamp>1574767516371</lastRenewalTimestamp>
                <evictionTimestamp>0</evictionTimestamp>
                <serviceUpTimestamp>1574766975765</serviceUpTimestamp>
            </leaseInfo>
            <metadata>
                <management.port>9080</management.port>
                <jmx.port>60432</jmx.port>
            </metadata>
            <homePageUrl>http://10.13.23.69:9080/</homePageUrl>
            <statusPageUrl>http://10.13.23.69:9080/actuator/info</statusPageUrl>
            <healthCheckUrl>http://10.13.23.69:9080/actuator/health</healthCheckUrl>
            <vipAddress>loja</vipAddress>
            <secureVipAddress>loja</secureVipAddress>
            <isCoordinatingDiscoveryServer>false</isCoordinatingDiscoveryServer>
            <lastUpdatedTimestamp>1574766976272</lastUpdatedTimestamp>
            <lastDirtyTimestamp>1574766975742</lastDirtyTimestamp>
            <actionType>ADDED</actionType>
        </instance>
    </application>
    <application>
        <name>FORNECEDOR</name>
        <instance>
            <instanceId>10.13.23.69:fornecedor:9081</instanceId>
            <hostName>10.13.23.69</hostName>
            <app>FORNECEDOR</app>
            <ipAddr>10.13.23.69</ipAddr>
            <status>UP</status>
            <overriddenstatus>UNKNOWN</overriddenstatus>
            <port enabled="true">9081</port>
            <securePort enabled="false">443</securePort>
            <countryId>1</countryId>
            <dataCenterInfo class="com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo">
                <name>MyOwn</name>
            </dataCenterInfo>
            <leaseInfo>
                <renewalIntervalInSecs>30</renewalIntervalInSecs>
                <durationInSecs>90</durationInSecs>
                <registrationTimestamp>1574767241152</registrationTimestamp>
                <lastRenewalTimestamp>1574767511190</lastRenewalTimestamp>
                <evictionTimestamp>0</evictionTimestamp>
                <serviceUpTimestamp>1574767240645</serviceUpTimestamp>
            </leaseInfo>
            <metadata>
                <management.port>9081</management.port>
                <jmx.port>60411</jmx.port>
            </metadata>
            <homePageUrl>http://10.13.23.69:9081/</homePageUrl>
            <statusPageUrl>http://10.13.23.69:9081/actuator/info</statusPageUrl>
            <healthCheckUrl>http://10.13.23.69:9081/actuator/health</healthCheckUrl>
            <vipAddress>fornecedor</vipAddress>
            <secureVipAddress>fornecedor</secureVipAddress>
            <isCoordinatingDiscoveryServer>false</isCoordinatingDiscoveryServer>
            <lastUpdatedTimestamp>1574767241152</lastUpdatedTimestamp>
            <lastDirtyTimestamp>1574767240642</lastDirtyTimestamp>
            <actionType>ADDED</actionType>
        </instance>
    </application>
</applications>

Contudo quando tendo realizar a compra tenho a seguinte exceção:

"message": "I/O error on GET request for \"http://fornecedor/info/GO\": Operation timed out (Connection timed out); nested exception is java.net.ConnectException: Operation timed out (Connection timed out)",

Os arquivos estão assim:

Loja

@SpringBootApplication
public class LojaApplication {

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

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

}
@Service
public class CompraService {

    @Autowired
    private RestTemplate client;

    public void realiza(CompraDTO compraDTO) {
        ResponseEntity<InfoFornecedorDTO> exchange = client.exchange(
                "http://fornecedor/info/" + compraDTO.getEndereco().getEstado(), 
                HttpMethod.GET, null, 
                InfoFornecedorDTO.class);

        System.out.println(exchange.getBody().getEndereco());
    }

}
10 respostas

O LojaApplication e CompraService estão corretos.

Posta aqui os arquivos application.yml das aplicações também, por favor.

Otávio, obrigado por responder!

Esqueci de mencionar que optei pelo banco de dados H2 para facilitar o estudo.

Aqui estão os arquivos de configuração:

Eureka

server:
  port: 8761
eureka:
  client:
    registerWithEureka: false
    fetchRegistry: false

Loja

spring:
  application:
    name: 'loja'

server:
  port: 9080

eureka:
  client:
    fetch-registry: true
    register-with-eureka: true
    service-url:
      defaultZone: http://localhost:8761/eureka

Fornecedor


spring:
  application:
    name: 'fornecedor'
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:fornecedor
    username: sa
    password: 
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: update

  h2:
    console:
      enabled: true
      path: '/h2-console'

server:
  port: 9081

eureka:
  client:
    fetch-registry: true
    register-with-eureka: true
    service-url:
      defaultZone: http://localhost:8761/eureka

Oi Igor, o que eu posso dizer é que vc pode não estar esperando o tempo suficiente para as instâncias se encontrarem através do Eureka. Você pode adicionar essa propriedade para que as instâncias se atualizem a cada 1 segundo: eureka.instance.leaseRenewalIntervalInSeconds=1

Adicione isso na Loja e no Fornecedor e veja se funciona pra vc.

Oi, Arthur, bom dia!

Primeiramente, obrigado por me responder!

Em segundo lugar, estou gostando muito do seu curso é bem prático e objetivo.

Ainda não funcionou com essa propriedade, segue o log:



2019-11-29 12:52:23.939  INFO 97568 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_LOJA/192.168.1.108:loja:9080: registering service...
2019-11-29 12:52:24.023  INFO 97568 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 9080 (http) with context path ''
2019-11-29 12:52:24.024  INFO 97568 --- [           main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 9080
2019-11-29 12:52:24.028  INFO 97568 --- [           main] b.c.microservicos.loja.LojaApplication   : Started LojaApplication in 2.906 seconds (JVM running for 3.545)
2019-11-29 12:52:24.031  INFO 97568 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_LOJA/192.168.1.108:loja:9080 - registration status: 204
2019-11-29 12:52:53.931  INFO 97568 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Disable delta property : false
2019-11-29 12:52:53.931  INFO 97568 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Single vip registry refresh property : null
2019-11-29 12:52:53.932  INFO 97568 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Force full registry fetch : false
2019-11-29 12:52:53.932  INFO 97568 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Application is null : false
2019-11-29 12:52:53.932  INFO 97568 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Registered Applications size is zero : true
2019-11-29 12:52:53.932  INFO 97568 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Application version is -1: false
2019-11-29 12:52:53.932  INFO 97568 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Getting all instance registry info from the eureka server
2019-11-29 12:52:53.968  INFO 97568 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : The response status is 200
2019-11-29 12:57:47.976  INFO 97568 --- [nio-9080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-11-29 12:57:47.976  INFO 97568 --- [nio-9080-exec-2] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-11-29 12:57:47.981  INFO 97568 --- [nio-9080-exec-2] o.s.web.servlet.DispatcherServlet        : Completed initialization in 5 ms
2019-11-29 12:57:48.177  INFO 97568 --- [nio-9080-exec-2] c.netflix.config.ChainedDynamicProperty  : Flipping property: fornecedor.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://fornecedor/info/GO": Operation timed out (Connection timed out); nested exception is java.net.ConnectException: Operation timed out (Connection timed out)] with root cause

Fico feliz por estar gostando. Vc poderia comitar o código da sua aplicação no github e disponibilizar aqui?

Arthur, tudo bem?

Primeiramente, muito obrigado pelo curso, tem sido muito bom para meu conhecimento, parabéns.

Estou com problema um problema quando chamado o POST: http://localhost:8080/compra

gera o erro abaixo:

{
    "timestamp": "2019-12-02T23:08:10.455+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "No instances available for fornecedor",
    "path": "/compra"
}

Segue trecho do erro no microservice da Loja

java.lang.IllegalStateException: No instances available for fornecedor
    at org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.execute(RibbonLoadBalancerClient.java:119) ~[spring-cloud-netflix-ribbon-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.execute(RibbonLoadBalancerClient.java:99) ~[spring-cloud-netflix-ribbon-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor.intercept(LoadBalancerInterceptor.java:58) ~[spring-cloud-commons-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.http.client.InterceptingClientHttpRequest$InterceptingRequestExecution.execute(InterceptingClientHttpRequest.java:92) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.http.client.InterceptingClientHttpRequest.executeInternal(InterceptingClientHttpRequest.java:76) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:735) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:670) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:579) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at br.com.microservice.loja.service.CompraService.realizaCompra(CompraService.java:20) ~[classes/:na]
    at br.com.microservice.loja.controller.CompraController.realizaCompra(CompraController.java:21) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-

Oi Huelton, que bom que está gostando. Você pode criar um tópico novo no fórum com a sua dúvida? Um mesmo tópico com muitas dúvidas é difícil de lidar. Posso acabar confundindo ou esquecendo de ajudar alguém. Tudo bem?

Arthur, boa tarde!

Segue a URL do GitHub: https://github.com/igor-ferreira-almeida/Microservicos-Spring-Clound

Ao subir para o GitHub eu baixei em outra máquina o código e funcionou perfeitamente, Arthur.

Está funcionando em um desktop Windows 10, eu estou tendo problemas em um Macbook.

Experimente alterar o nome da aplicação removendo as aspas, de:

spring:
  application:
    name: 'fornecedor'

para:

spring:
  application:
    name: fornecedor