Spring Cloud API Gateway routing not working - spring-boot

I have designed a micro service prototype using below technologies
Eureka Server
a service
Spring Cloud API Gateway
Above mentioned service are registered in the Eureka Server
API Gateway routing Configuration
server.port=8080
eureka.client.serviceUrl.defaultZone = http://localhost:8083/eureka
spring.application.name=ApiGateway
spring.cloud.gateway.discovery.locator.enabled=true
spring.cloud.gateway.discovery.locator.lower-case-service-id=true
spring.cloud.gateway.routes[0].id=service1
spring.cloud.gateway.routes[0].uri=lb://MICROSERVICE1
spring.cloud.gateway.routes[0].predicates[0]=Path=/service1/**
The service Configuration
server.port=8081
server.address=127.0.0.1
eureka.client.serviceUrl.defaultZone = http://localhost:8083/eureka
spring.application.name=MicroService1
error.whitelabel.enabled= false
Controller
#RestController
#RequestMapping("/service1")
public class HomeController {
#GetMapping("/message")
public String hello() {
return "response from micro service1";
}
}
When I send a request to the gateway it's showing the below error
2020-12-16 22:26:09.770 ERROR 16700 --- [ctor-http-nio-3] a.w.r.e.AbstractErrorWebExceptionHandler : [d3334561-1] 500 Server Error for HTTP GET "/service1/message"
java.net.UnknownHostException: failed to resolve 'LAPTOP-KU56B6A8' after 3 queries
at io.netty.resolver.dns.DnsResolveContext.finishResolve(DnsResolveContext.java:1013) ~[netty-resolver-dns-4.1.55.Final.jar:4.1.55.Final]
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
|_ checkpoint ⇢ org.springframework.cloud.gateway.filter.WeightCalculatorWebFilter [DefaultWebFilterChain]
|_ checkpoint ⇢ HTTP GET "/service1/message" [ExceptionHandlingWebHandler]
How can we solve the above issue?

Add eureka.instance.hostname=localhost in both the microservices instances this will work and not give an error

i have modified the API Gate Way routing Configuration like below
spring.cloud.gateway.routes[0].id=service1
spring.cloud.gateway.routes[0].uri=http://localhost:8081/service1/
spring.cloud.gateway.routes[0].predicates[0]=Path=/service1/**
Now is working fine

Add this bean in your API gateway and you are good to go.
#Bean
public HttpClient httpClient() {
return HttpClient.create().resolver(DefaultAddressResolverGroup.INSTANCE);
}

Add below to both gateway and individual microservice fix the issue
eureka.instance.hostname=localhost
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:8010/eureka/

Add in your application.properties:
spring.cloud.discovery.enabled=true

I have modified my .yaml file with this configuration.
Issue resolved for me.
**server:
port: 9999
spring:
application:
name: gateway-ws
cloud:
gateway:
discovery:
locator:
enabled: true
routes:
- id: userService
uri: http://user-service/
predicates:
- Path=/user/**
- id: contactService
uri: http://contact-service/
predicates:
- Path=/contact/**
eureka:
client:
service-url:
defaultZone: http://localhost:8085/eureka**

This is the only solution works among all of the answers above.
#Bean
public HttpClient httpClient() {
return HttpClient.create().resolver(DefaultAddressResolverGroup.INSTANCE);
}
This is the default behavior, so no effect.
spring.cloud.discovery.enabled=true
This has nothing to do with the discovery client.
It is related with the discovery server.
eureka.instance.hostname=localhost
So if you don't know, just don't mess it up with wrong directions.

hello jebji if you still have this problem
add
spring.cloud.discovery.enabled=true
in application.properties

Only Add the following property into your API gateway:
spring.cloud.discovery.enabled=true
Make sure you already added DevTool maven dependency into your API gateway project but if not then restart it.

add flowing property in application.property file of all eruka client microservice and api gateway , i face same issue and resolve doing same activity
spring.cloud.discovery.enabled=true
spring.cloud.gateway.discovery.locator.lower-case-service-id= true
spring.cloud.gateway.discovery.locator.enabled= true
eureka.instance.hostname=localhost

after adding all the above properties then also if you are facing issue then try the below one,
don't use lb://albums_service , but use lb://albums-service .Because URI don‘t support underline.

You can add the following in application.yml file
spring:
cloud:
gateway:
routes:
- id: test-service
uri: lb://MICROSERVICE1
predicates:
- Path=/microservice1/**
filters:
- RewritePath=/microservice1/(?<segment>.*), /$\{segment}
with this it should works.
Like let say if your microservice1 is url is
localhost:8081/service1/message
then you can define the base path of your microservice1 in api-gateway by setting up the path as i did in above configuration.

The error message is "failed to resolve 'LAPTOP-KU56B6A8'".
This is an DNS issue.
You can set eureka.instance.prefer-ip-address=true in the service.
So it will register with its ip at Eureka and the DNS issue can be avoided.
This is actually the same issue as this QUESTION.
With this ANSWER

Related

Not able to resolve feign client name from application yml

I have a spring boot app and i am trying to use feign client to make a request to an endpoint but its not able to resolve feign client name from application yml.
My application yml has following code :
ribbon:
eureka:
enabled: false
beacon:
ribbon:
isSecure: true
listOfServers: https://beacon.org
My interface look like this :
#FeignClient("beacon")
public interface BeaconClient {
#GetMapping("/api/organizations")
List<Org> getOrgs();
}
I am getting an error 500 internal server error because i see that it making a request to http://beacon/api/organizations endpoint instead of https://beacon.org/api/organizations
Your code is correct. The default feign Logger is misleading. http://beacon/.. that you see in the log isn't indicative of actual url that is being called. The actual request is resolved with https://beacon.org/...

404 error in spring cloud gateway for every alternate request

I am encountering a very peculiar problem in spring cloud gateway. Every alternate request returns a 404. This happens across all services I've configured in the api-gateway without exception. I don't even know where to start to debug this problem.
Here's my application.yml file for common config.
server:
port: 8080
ssl:
enabled: true
key-store: classpath:keystore.p12
key-store-password: password
key-store-type: pkcs12
key-alias: tomcat
security:
require-ssl=true:
logging:
level:
org:
springframework:
cloud.gateway: DEBUG
http.server.reactive: DEBUG
web.reactive: DEBUG
spring:
application:
name: api-gateway
cloud:
gateway:
httpclient:
ssl:
useInsecureTrustManager: true
Here's my java config file
#EnableWebFluxSecurity
public class SecurityConfig {
#Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http,
ReactiveClientRegistrationRepository clientRegistrationRepository) {
// Authenticate through configured OpenID Provider
http.oauth2Login();
// Also logout at the OpenID Connect provider
http.logout(logout -> logout.logoutSuccessHandler(new OidcClientInitiatedServerLogoutSuccessHandler(
clientRegistrationRepository)));
// Require authentication for all requests
http.authorizeExchange().anyExchange().authenticated();
// Allow showing /home within a frame
http.headers().frameOptions().mode(Mode.SAMEORIGIN);
// Disable CSRF in the gateway to prevent conflicts with proxied service CSRF
http.csrf().disable();
return http.build();
}
}
Here's the spring profile specific config file that gets loaded on top of the common application.yml file.
spring:
security:
oauth2:
client:
provider:
keycloak:
issuerUri: http://localhost:9080/auth/realms/mylocal
userNameAttribute: preferred_username
registration:
keycloak:
clientId: api-gateway-client
clientSecret: abcdefgh-ijkl-mnop-qrst-uvwxyz5d6a9
cloud:
gateway:
default-filters:
- TokenRelay
routes:
- id: news
uri: http://localhost:8082/news
predicates:
- Path= /news/**
- id: customers
uri: http://localhost:8083/customers
predicates:
- Path= /boards/**
- id: search
uri: http://localhost:8085/search
predicates:
- Path= /search/**
Hey i got the issue recently too, I figure out that it was the load balancing the issue. Make sure that your spring.application.name of the microservice that you try to contact are all in capital letter (EXAMPLE) especially if you use Eureka. (hope it helps)
I had a similar issue. The reason was in registration of several services under the same application name in my Eureka server. Just like this:
Eureka instances screenshot
Those are completely different services, but they are registered under one application name. So when a request is made through load balancer, the latter tries to use both of the service urls. One service is able to serve request correctly, but another one may know nothing about the requested path, that is why 404 is returned.
Check if there are two or more microservices using the same spring.application.name and registered with eureka.
I know it's an old question... But might help future readers.
hey, here is the simplest solution I found for myself, in the browser
url, instead of 'localhost', give your system's name.
ex:
http://hp:8083/SERVICE-NAME/customers/**
also make sure to name all your spring application in uppercase.

Spring cloud gateway default routing doesn't work

I want enable default routing in my spring cloud gateway (no zuul) by service ids registered in eureka (application names) but I always got 404 error.
In my chat service's bootstrap.yml
I have defined application name
spring:
application:
name: chat-service
and in application properties:
eureka:
instance:
preferIpAddress: true
client:
healthcheck:
enabled: true
serviceUrl:
defaultZone: http://${EUREKA_HOST:localhost}:${EUREKA_PORT:8761}/eureka/
when I go to eureka's dashboard I can see registered my chat service and gateway as well.
Eureka's configuration in gateway application is same as chat service, but I also have this:
spring:
application:
name: gateway
cloud:
gateway:
discovery:
locator:
enabled: true
and next I also tried add explicit routes which din't work as well, but if I have discovery locator enabled set to true this shouldn't be needed right?
routes:
- id: chat-service-route
uri: lb://chat-service
predicates:
- Path=**
I created test endpoint which I tried call directly on chat service and also with gateway. Direct call works fine so issue will be with routing.
#RestController
#RequestMapping
public class TestController {
#GetMapping
public String test() {
return "chat-service ready";
}
}
What I did wrong? I am little desperate. I am using spring boot 2.2.2 and Hoxton.RELEASE cloud dependencies version
Try removing explicit routes and add below property to application yml. This works for me.
spring:
cloud:
gateway:
discovery:
locator:
lower-case-service-id: true

Rarely getting ClientException and ZuulException in spring boot, eureka, zuul, ribbon framework

I have configured my project architecture using Spring Boot, Eureka, Zuul, Ribbon frameworks.
Its working fine but sometimes (rarely) getting the following exceptions:
Caused by: com.netflix.client.ClientException: Load balancer does not have available server for client: service1
Caused by: com.netflix.hystrix.exception.HystrixRuntimeException: service1 timed-out and no fallback available.
Below are my services configurations:
Have a look and please let me know if I missed anything which causing the issues for above exceptions.
eureka service application.properties:
server.port=8070
spring.application.name=eureka_service
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.instance.hostname=localhost
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:8070/eureka/
logging.level.com.netflix.eureka=OFF
logging.level.com.netflix.discovery=OFF
zuul service application.properties:
server.port=8071
spring.application.name=zuul_service
zuul.prefix=/api
zuul.routes.service1.path=/service1/**
zuul.routes.service1.service-id=service1
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
eureka.instance.hostname=localhost
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:8070/eureka/
ribbon.eureka.enabled=true
service1 application.properties:
server.port=8072
spring.application.name=service1
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
eureka.instance.hostname=localhost
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:8070/eureka/
ribbon.eureka.enabled=true
Please let me know if I need to add any other configuration to resolve ?
Thanks.
You can try to increase the Ribbon timeout by setting for example:
ribbon.ReadTimeout=10000
If above code doesn't work you can try by disabling the timeout:
hystrix.command.default.execution.timeout.enabled=false

Feign Client Prioritizing URL's in yaml over Eureka

I have a Spring Boot application which serves as a Eureka client. The application has the need to call another micro-service through REST, and I wish to make this call using Feign. The issue I am having is, my application is trying to lookup the service name in Eureka, when it is only defined in my applications yaml file.
I apologize for the hard to follow explanation, hopefully the following code snippets will help clarify.
Feign client:
#FeignClient("foo")
#Component
public interface FooServiceProxy{
#RequestMapping(value = "/balance", method = RequestMethod.POST, produces = "application/json")
ServiceResponse execute(ServiceRequest serviceRequest);
}
In my controller who calls this Feign client, the FooServiceProxy is defined using #AutoWired:
#Autowired
private FooServiceProxy fooServiceProxy;
My yaml file is as follows:
spring:
application:
name: app-name
server:
port: 8080
foo:
ribbon:
listOfServers: http://hostname:8081/balance
eureka:
client:
fetchRegistry: false
serviceUrl:
defaultZone: http://eurekasrver:8761/eureka/
My issue is, during run-time, the following error is thrown:
java.lang.RuntimeException: com.netflix.client.ClientException: Load balancer does not have available server for client: foo
Interestingly, if I remove the #EnableEurekaClient annotation from the application, everything works. I believe I understand the problem which is that instead of looking up the server for foo in my yaml file, because the application is a Eureka client, Feign is going straight to Eureka to lookup a server ip, then failing as none can be found. Despite seeming to understand the problem, I have been unable to find a solution online or to think of one myself.
Any help will be appreciated.
Thank you!
Concerning this question, you should take in account that when eureka is on your classpath, all ribbon configuration are charged by eureka, so it'll use eureka server's list.
Spring Cloud uses #RibbonClient to configure the types used by ribbon, like server list. If you have eureka on the classpath, by default it uses the eureka server list (hence your need for the flag to disable eureka).
Commented by spencergibb https://github.com/spring-cloud/spring-cloud-netflix/issues/564
You can try either by adding the NIWSServerListClassName configuration:
`someservice.ribbon:
NIWSServerListClassName:com.netflix.loadbalancer.ConfigurationBasedServerList
listOfServers: server1:80`
Or try the solution proposed in this issue https://github.com/spring-cloud/spring-cloud-netflix/issues/564

Resources