Showing posts with label Eureka Client. Show all posts
Showing posts with label Eureka Client. Show all posts

Wednesday, June 4, 2025

SpringBoot: Assign a port number dynamically

 Most of the time we give the port number in the application properties files under "server.port"

Or lese when we start the application eg: run as jar file with java -jar using -D option we can asign a port number

java -jar -Dserver.port=8888

Or in running application in IDE , you can configure the port number which is more or less the same.


Solution:

Simply assign the "server.port" to zero

server.port=0

This will dynamically assign a port at run time.


So how find the dynamic port number

1. you can find from application start console logs

2. Form Eureka server

    Simply click the lik , it will go to actuator point with the port number

eg:http://user-home:64192/actuator/info



For your info, i will put a sample log also.

--------------------------------------------------------------------------------------------------------

2025-06-04T15:03:50.374+05:30  WARN 19248 --- [rest-client-with-feign] [           main] iguration$LoadBalancerCaffeineWarnLogger : Spring Cloud LoadBalancer is currently working with the default cache. While this cache implementation is useful for development and tests, it's recommended to use Caffeine cache in production.You can switch to using Caffeine cache, by adding it and org.springframework.cache.caffeine.CaffeineCacheManager to the classpath.

2025-06-04T15:03:50.461+05:30  INFO 19248 --- [rest-client-with-feign] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 64192 (http) with context path '/'

2025-06-04T15:03:50.476+05:30  INFO 19248 --- [rest-client-with-feign] [           main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 64192

2025-06-04T15:03:50.488+05:30  INFO 19248 --- [rest-client-with-feign] [           main] o.s.c.n.eureka.InstanceInfoFactory       : Setting initial instance status as: STARTING

2025-06-04T15:03:50.530+05:30  INFO 19248 --- [rest-client-with-feign] [           main] com.netflix.discovery.DiscoveryClient    : Initializing Eureka in region us-east-1

-----------------------------------------------------------------------------------------------------




Tuesday, June 3, 2025

Error in console running simple rest client using RestTemplate : java.net.UnknownHostException: greet-service

Here Problem is whichever configured application cannot find the host=greet-service. If you have a application with hostname, the request will go to it, but in this scenario we are looking at service registered with Discovery service.

1. Service main Spring Boot class  is missing @EnableDiscoveryClient and also 

2. maven POM dependency for Discovery client


@SpringBootApplication

public class GreetServiceWithEurekaApplication {

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

}

Sample Controller

@RestController
public class GreetClientController {

private RestTemplate restTemplate = new RestTemplate();

@RequestMapping("/greet-call")
Greet greet() {
//Phase 1 - without Discovery/Eureka client
// Greet greet = restTemplate.getForObject("http://localhost:8090/greet", Greet.class);
//With Discovery client - Now we can use service name - and with other option available via eureka server
// you need to configure DiscoveryClient - else cannot find hte hostname "greet-service" which is registered inEureka server
Greet greet = restTemplate.getForObject("http://greet-service/greet", Greet.class);
return greet;
}
}


Solution Steps

1. Add Discovery Client dependency to POM

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

you cannot simply add the dependency unless you don't have the dependency management. So add below dependency management block and property to identify the version.

<properties>

<spring-cloud.version>2025.0.0</spring-cloud.version>
</properties>


<!--    added dependency mgt after adding discovery client dependency-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

2. Add  Discovery Client Enable annotations - @EnableDiscoveryClient

3. Make RestTemplate Autowired. 

4. You need to define the RestTemplate bean 

5. RestTamplate bean must be Load balanced

6. Make sure Discovery server and corresponding service greet-service up and running

So after this code blocks of main class and Sample controller would be like below

package com.example.rest_client;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
public class RestClientApplication {

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

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


package com.example.rest_client.controller;

import com.example.rest_client.model.Greet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class GreetClientController {

// private RestTemplate restTemplate = new RestTemplate();
@Autowired
private RestTemplate restTemplate;

@RequestMapping("/greet-call")
Greet greet() {
//Phase 1 - without Discovery/Eureka client
// Greet greet = restTemplate.getForObject("http://localhost:8090/greet", Greet.class);
//With Discovery client - Now we can use service name - and with other option available via eureka server
// you need to configure DiscoveryClient - else cannot find hte hostname "greet-service" which is registered inEureka server
Greet greet = restTemplate.getForObject("http://greet-service/greet", Greet.class);
return greet;
}
}


So when you call with

http://localhost:8095/greet-call

you should get a response like below.

{"message":"Demo with RestTemplate"}


Below is the full stacktrace:

----------------------------

 2025-06-03T16:54:02.056+05:30 ERROR 26616 --- [rest-client] [nio-8095-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://greet-service/greet": greet-service] with root cause


java.net.UnknownHostException: greet-service

at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:567) ~[na:na]

at java.base/java.net.Socket.connect(Socket.java:751) ~[na:na]

at java.base/java.net.Socket.connect(Socket.java:686) ~[na:na]

at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:183) ~[na:na]

at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:531) ~[na:na]

at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:636) ~[na:na]

at java.base/sun.net.www.http.HttpClient.<init>(HttpClient.java:280) ~[na:na]

at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:386) ~[na:na]

at java.base/sun.net.www.http.HttpClient.New(HttpClient.java:408) ~[na:na]

at java.base/sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1304) ~[na:na]

at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1237) ~[na:na]

at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1123) ~[na:na]

at java.base/sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:1052) ~[na:na]

at org.springframework.http.client.SimpleClientHttpRequest.executeInternal(SimpleClientHttpRequest.java:79) ~[spring-web-6.2.7.jar:6.2.7]

at org.springframework.http.client.AbstractStreamingClientHttpRequest.executeInternal(AbstractStreamingClientHttpRequest.java:71) ~[spring-web-6.2.7.jar:6.2.7]

at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:81) ~[spring-web-6.2.7.jar:6.2.7]

at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:900) ~[spring-web-6.2.7.jar:6.2.7]

at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:801) ~[spring-web-6.2.7.jar:6.2.7]

at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:415) ~[spring-web-6.2.7.jar:6.2.7]

at com.example.rest_client.controller.GreetClientController.greet(GreetClientController.java:19) ~[classes/:na]

at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) ~[na:na]

at java.base/java.lang.reflect.Method.invoke(Method.java:580) ~[na:na]

at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:258) ~[spring-web-6.2.7.jar:6.2.7]

at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:191) ~[spring-web-6.2.7.jar:6.2.7]

at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:118) ~[spring-webmvc-6.2.7.jar:6.2.7]

at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:986) ~[spring-webmvc-6.2.7.jar:6.2.7]

at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:891) ~[spring-webmvc-6.2.7.jar:6.2.7]

at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-6.2.7.jar:6.2.7]

at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1089) ~[spring-webmvc-6.2.7.jar:6.2.7]

at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:979) ~[spring-webmvc-6.2.7.jar:6.2.7]

at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014) ~[spring-webmvc-6.2.7.jar:6.2.7]

at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:903) ~[spring-webmvc-6.2.7.jar:6.2.7]

at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:564) ~[tomcat-embed-core-10.1.41.jar:6.0]

at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885) ~[spring-webmvc-6.2.7.jar:6.2.7]

at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658) ~[tomcat-embed-core-10.1.41.jar:6.0]

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:195) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:140) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) ~[tomcat-embed-websocket-10.1.41.jar:10.1.41]

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:164) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:140) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-6.2.7.jar:6.2.7]

at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.2.7.jar:6.2.7]

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:164) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:140) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-6.2.7.jar:6.2.7]

at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.2.7.jar:6.2.7]

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:164) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:140) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-6.2.7.jar:6.2.7]

at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.2.7.jar:6.2.7]

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:164) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:140) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:483) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:116) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:344) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:398) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:903) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1740) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1189) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:658) ~[tomcat-embed-core-10.1.41.jar:10.1.41]

at org.apache.tomcat.util.threads.TaskThread$WrappingRunn



---------------------

Next StackStrace

When RestTemplate bean is not configured.

---------------------------------

2025-06-03T17:50:35.259+05:30  INFO 18284 --- [rest-client] [           main] .s.b.a.l.ConditionEvaluationReportLogger : 


Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.

2025-06-03T17:50:35.288+05:30 ERROR 18284 --- [rest-client] [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 


***************************

APPLICATION FAILED TO START

***************************


Description:


Field restTemplate in com.example.rest_client.controller.GreetClientController required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.


The injection point has the following annotations:

- @org.springframework.beans.factory.annotation.Autowired(required=true)



Action:


Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.



Step - Solution - Still we have the problem

----------

Define Bean - Here at main Spring Boot class for time being

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

With this also Still you will get the above error cannot find the hostname with {service-name}

to solve completely , you need to add the @LoadBalanced annotation to configure with Eureka

Solution

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



Complete Code with imports

package com.example.rest_client;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
public class RestClientApplication {

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

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


Wednesday, June 14, 2023

MS - chapter 3 - Register services with Eureka

 Tech Stack

Java 8, Maven, Springboot 3.10 , 

Scenario

Here we will register create web services with Eureka server


1. Add Eureka client dependency

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

Here if dependency cannot download add version under properties

<properties>
<java.version>17</java.version>
<spring-cloud.version>2022.0.3</spring-cloud.version>
</properties>

And the dependency Management to download

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>


2. Inject Eureka client dependency at main class - register service with Eureka server

Here you can set the name of the service also

@Autowired
@Lazy
private EurekaClient eurekaClient;

@Value("${spring.application.name}")
private String appName;


3. Register Service With Eureka server / Add service as a Eureka client

Add below properties

Note: My service name is "student"

spring.application.name=student
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/

4. You can start the client. Now your client will be registered with the Eureka Server.

Note: If you are using a database, make sure it is up and running

In here, we are using Mysql.

If it is not running you can start using command "mysqld --console"


Below is the Important Code base


Main Class

package com.demo.micro.student;

import com.netflix.discovery.EurekaClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Lazy;


@SpringBootApplication
public class StudentApplication {

@Autowired
@Lazy
private EurekaClient eurekaClient;

@Value("${spring.application.name}")
private String appName;
public static void main(String[] args) {
SpringApplication.run(StudentApplication.class, args);
}

}


application.properties for your reference

server.port=8203
spring.datasource.url=jdbc:mysql://localhost:3306/student_mgt
spring.datasource.username=root
spring.datasource.password=root

# for Spring Boot 2
# spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
# for Spring Boot 3
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQLDialect
spring.jpa.show-sql=false
spring.jpa.generate-ddl=true
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

spring.application.name=student
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/

References

https://cloud.spring.io/spring-cloud-netflix/multi/multi__service_discovery_eureka_clients.html

https://www.baeldung.com/spring-cloud-netflix-eureka