Spring Data Elastic search in a Spring Boot application - java

I have a Spring Boot application and I want to use Elastic search 2.2.0 standalone (not the embedded server) in it, I wanna use Spring Data Elastic search, so what are the Elastic search supported versions by Spring Data and how can I configure it to connect to elasticsearch instance running in localhost:9200?
Actually, I tried adding this options to my application.properties file:
spring.data.elasticsearch.repositories.enabled=true
spring.data.elasticsearch.cluster-nodes=localhost:9200
And later, I created this configuration class:
#Configuration
public class ElasticConfig {
#Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchTemplate(client());
}
#Bean
public Client client() {
TransportClient client = new TransportClient();
TransportAddress address = new InetSocketTransportAddress(
"localhost",9200);
client.addTransportAddress(address);
return client;
}
}
I get this stacktrace:
2016-04-28 00:03:52.246 INFO 25613 --- [ restartedMain]
org.elasticsearch.plugins : [Aardwolf] loaded [], sites
[] 2016-04-28 00:04:01.356 INFO 25613 --- [ restartedMain]
org.elasticsearch.client.transport : [Aardwolf] failed to get
node info for
[#transport#-1][fathi-HP-Pavilion-g6-Notebook-PC][inet[localhost/127.0.0.1:9200]], disconnecting...
org.elasticsearch.transport.ReceiveTimeoutTransportException:
[][inet[localhost/127.0.0.1:9200]][cluster:monitor/nodes/info]
request_id [0] timed out after [5001ms] at
org.elasticsearch.transport.TransportService$TimeoutHandler.run(TransportService.java:529)
~[elasticsearch-1.5.2.jar:na] at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
~[na:1.8.0_77] at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
~[na:1.8.0_77] at java.lang.Thread.run(Thread.java:745)
~[na:1.8.0_77]
2016-04-28 00:04:01.512 ERROR 25613 --- [ restartedMain]
.d.e.r.s.AbstractElasticsearchRepository : failed to load
elasticsearch nodes :
org.elasticsearch.client.transport.NoNodeAvailableException: None of
the configured nodes are available: []

I got this answer from the ES forum and it worked for me:
First, Spring Data Elasticsearch works officially with ES 1.x versions(for me it worked with 1.7.1).
Second, the port used in the configuration must be 9300
I made these changes and it worked pretty perfect.

As Jemli said you will need to use the port 9300.
Also make sure that your elastiscsearch client and server are using the same major version. If you are using elasticsearch 2.x you will need to update spring boot to the latest version ( > 1.4.0.RC1).
Please have a look to this post if you need more information:
http://ignaciosuay.com/how-to-connect-spring-boot-to-elasticsearch-2-x-x/

I read official document.
If use Java Config,please try:
#Configuration
#EnableElasticsearchRepositories(basePackages = "org/springframework/data/elasticsearch/repositories")
static class Config {
#Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchTemplate(nodeBuilder().local(true).node().client());
}
}
If use XML, please try:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/data/elasticsearch
http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd">
<elasticsearch:transport-client id="client" cluster-nodes="localhost:9300,someip:9300" />
</beans>
You can read http://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.introduction

Related

Spring Boot Kafka StreamsConfig or ConsumerConfig from application.yaml not applying

I have a very simple spring boot project with a KTable and I want to customize my configuration in application.yml, but the config seems to not be applied. This is my configuration file application.yml
spring:
kafka:
bootstrap-servers: ${KAFKA_BOOTSTRAP_SERVERS:localhost:9092}
streams:
application-id: ${APPLICATION_ID:train-builder-processor}
buffered-records-per-partition: 50
consumer:
auto-offset-reset: earliest
max-poll-records: ${MAX_POLL_RECORDS:50}
max-poll-interval-ms: ${KAFKA_CONSUMER_MAX_POLL_INTERVAL_MS:1000}
properties:
spring:
json:
trusted:
packages:
- com.example.kafkastream
However, when starting the application the log outputs the following:
2022-03-03 08:20:06.992 INFO 32989 --- [ main] s.r.s.m.t.TrainBuilderApplication : Starting TrainBuilderApplication using Java 16.0.2 on MAPFVFG90ZQQ05P with PID 32989 (/Users/xxx/dev/train-builder-processor/target/classes started by xxx in /Users/xxx/dev/train-builder-processor)
2022-03-03 08:20:06.995 DEBUG 32989 --- [ main] s.r.s.m.t.TrainBuilderApplication : Running with Spring Boot v2.6.3, Spring v5.3.15
2022-03-03 08:20:06.995 INFO 32989 --- [ main] s.r.s.m.t.TrainBuilderApplication : No active profile set, falling back to default profiles: default
2022-03-03 08:20:08.856 INFO 32989 --- [ main] org.apache.kafka.streams.StreamsConfig : StreamsConfig values:
acceptable.recovery.lag = 10000
application.id = test.train-builder-processor
application.server =
bootstrap.servers = [localhost:9092]
buffered.records.per.partition = 1000
... (a bunch of other configs)
ConsumerConfig:
...
max.poll.interval.ms = 300000
max.poll.records = 1000
...
Below is the simple application class I'm using:
#EnableKafka
#EnableKafkaStreams
#SpringBootApplication
public class TrainBuilderApplication {
...
#Autowired
private TrainIdMapper trainIdMapper;
#Autowired
private TrainBuilder trainBuilder;
public static void main(String[] args) {
SpringApplication.run(TrainBuilderApplication.class, args);
}
#Bean
public KTable<String, Train> trainTable(StreamsBuilder kStreamBuilder) {
return kStreamBuilder
.stream(Pattern.compile(sourceTopicsPattern), Consumed.with(Serdes.String(), myJsonSerde))
.map(trainIdMapper)
.filter((key, value) -> key != null)
.groupByKey(Grouped.with(Serdes.String(), mySerde))
.aggregate(() -> null, trainBuilder, trainStore);
}
}
The values from my application.yml seems to be ignored. What could be the cause of this? What am I missing? Thanks in advance!
So I figured it out with the help of How do I properly externalize spring-boot kafka-streams configuration in a properties file?.
Apparently, consumer and producer configs are completely separated from streams config when using a KStream. To set specific properties for the consumer of the kafka stream one must use "additional properties" like so:
spring:
kafka:
bootstrap-servers: ${KAFKA_BOOTSTRAP_SERVERS,localhost:9092}
streams:
application-id: ${APPLICATION_ID:train-builder-processor}
cache-max-size-buffering: 1048576
cleanup.on-shutdown: ${CLEANUP_ON_SHUTDOWN:false}
properties:
max:
poll:
records: 50
which was a bit unintuitive, but it works. Hope this can help someone in the future!

Apache Camel route with MongoDB gives an error No bean could be found in the registry

I am trying into implement a route to insert content into MongoDB. Below is the route I tried and it gives me an error:
Caused by: org.apache.camel.NoSuchBeanException: No bean could be found in the registry for: localhost:27017 of type: com.mongodb.client.MongoClient
from("rabbitmq:localhost:5672/tasks?autoDelete=false&routingKey=camel&queue=task_queue")
.bean(itemDetails, "consumeItemDetails(${exchange})")
.to("mongodb://localhost:27017?database=ItemDB&collection=ItemDetails&operation=save");
I was not sure where and how to define a bean of type MongoClient and how I can pass the host and port numbers as parameters. Could anyone please guide me on this?
You need to declare a MongoClient bean. If you're running your application through Spring Boot (starter), it will provide your app with a bean named mongo. Otherwise, you need to follow Chanfir's advice.
In your route definition , you need to add the beanId as following :
from("rabbitmq:localhost:5672/tasks?autoDelete=false&routingKey=camel&queue=task_queue")
.bean(itemDetails, "consumeItemDetails(${exchange})")
.to("mongodb:mongoBean?database=ItemDB&collection=ItemDetails&operation=save");
And define a bean of type MongoClient with beanId mentionned in your xml/annotation configuration then define database connection params inside the bean :
Example using Spring xml configuration :
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<mongo:mongo-client id="mongoBean" host="${mongo.url}" port="${mongo.port}" credentials="${mongo.user}:${mongo.pass}#${mongo.dbname}">
<mongo:client-options write-concern="NORMAL" />
</mongo:mongo-client>
</beans>
Example using Annotations :
#Configuration
public class MongoConfig extends AbstractMongoClientConfiguration {
#Override
protected String getDatabaseName() {
return "test";
}
#Override
public MongoClient mongoClient() {
ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/test");
MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
.applyConnectionString(connectionString)
.build();
return MongoClients.create(mongoClientSettings);
}
#Override
public Collection getMappingBasePackages() {
return Collections.singleton("com.baeldung");
}
}
To be able to execute the code using Spring Boot 2.7.3 and Camel 3.18.2, I have to explicitely register the Mongo client when loading the route:
#Autowired
MongoConfig mongoConfig;
then :
context.getRegistry().bind("connectionBean", mongoConfig.mongoClient());
Is there a way to automatically register the Mongo Client?
you can easily add a bean inside your Application class if you are developing using Java DSL, like this:
#Bean("myconnection")
public MongoClient mongo() {
return new MongoClient("localhost", 27107);
}

Spring boot 2 connection to rabbitmq via Apache Camel

I have problem with connection to rabbitmq via Apache Camel on Spring Boot 2.
I did following steps:
My dependencies:
implementation "org.apache.camel:camel-spring-boot-starter:${camelVersion}"
implementation "org.apache.camel:camel-jackson-starter:${camelVersion}"
implementation "org.apache.camel:camel-core:${camelVersion}"
implementation "org.apache.camel:camel-rabbitmq-starter:${camelVersion}"
implementation "org.springframework.boot:spring-boot-starter-amqp"
Application.yaml
spring:
rabbitmq:
dynamic: true
host: 192.168.1.1
port: 5672
username: X
password: Y
And I have following route:
#Component
public class BasicRoute extends RouteBuilder {
#Override
public void configure() throws Exception {
from("direct:loggerQueue")
.id("loggerQueue")
.to("rabbitmq://TEST-QUEUE.exchange?queue=TEST-QUEUE.queue&autoDelete=false&connectionFactory=#rabbitConnectionFactory")
.end();
}
}
Finnaly I have still following issue:
2019-03-06 12:46:05.766 WARN 19464 --- [ restartedMain] o.a.c.c.rabbitmq.RabbitMQProducer : Failed to create connection. It will attempt to connect again when publishing a message.
java.net.ConnectException: Connection refused: connect
Connection seems ok, I tested it. Something is bad with rabbitConnectionFactory.
I don't know what I have bad.
The problem appears to be that RabbitMQComponent is expecting to find a connection factory of type com.rabbitmq.client.ConnectionFactory.
However, the springboot auto-configure is creating a connection factory of type org.springframework.amqp.rabbit.connection.CachingConnectionFactory.
So, whenever the RabbitMQComponent attempts to find the appropriate connection factory, because it is looking for the specific type, and because it does not subclass the rabbitmq ConnectionFactory, it returns a null value, and fails to use the appropriate host name and configuration parameters specified in your application.yml.
You should also see the following in your log if you have debug level set:
2019-12-15 17:58:53.631 DEBUG 48710 --- [ main] o.a.c.c.rabbitmq.RabbitMQComponent : Creating RabbitMQEndpoint with host null:0 and exchangeName: asterix
2019-12-15 17:58:55.927 DEBUG 48710 --- [ main] o.a.c.c.rabbitmq.RabbitMQComponent : Creating RabbitMQEndpoint with host null:0 and exchangeName: asterix-sink
EDIT:
The CachingConnectionFactory is configured with the required Rabbit connection factory as part of the autoconfiguration. However, you need to provide a link to the correct factory.
Therefore, you need to add a #Bean to disambiguate.
#Configuration
#RequiredArgsConstructor
public class CamelConfig {
private final CachingConnectionFactory rabbitConnectionFactory;
#Bean
com.rabbitmq.client.ConnectionFactory rabbitSourceConnectionFactory() {
return rabbitConnectionFactory.getRabbitConnectionFactory();
}
}
and in your endpoint configuration:
rabbitmq:asterix?connectionFactory=#rabbitSourceConnectionFactory
Note that the # is optional, as it gets stripped out within the code when it is trying to find the rabbit connection factory bean.
In your application.yml, configure the connection parameters (the url is no longer included in the endpoint URI).
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest

Apache camel Connection pool timeout with restlet even after configuring component options

I have a camel Java DSL route which invokes a restlet endpoint. And the route works without any issues when I hit the same manually. But, when I try to pump a larger number of requests through code I'm getting "Timeout waiting for connection from pool"
And the following is stackt-race of the same:
2016-01-29 14:09:38.650 WARN 20256 --- [pool-3-thread-2] org.restlet : An error occurred during the communication with the remote HTTP server.org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
at org.apache.http.impl.conn.tsccm.ConnPoolByRoute.getEntryBlocking(ConnPoolByRoute.java:412)
at org.apache.http.impl.conn.tsccm.ConnPoolByRoute$1.getPoolEntry(ConnPoolByRoute.java:298)
at org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager$1.getConnection(ThreadSafeClientConnManager.java:238)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:423)
at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:863)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57)
at org.restlet.ext.httpclient.internal.HttpMethodCall.sendRequest(HttpMethodCall.java:339)
at org.restlet.engine.adapter.ClientAdapter.commit(ClientAdapter.java:105)
at org.restlet.engine.adapter.HttpClientHelper.handle(HttpClientHelper.java:119)
at org.restlet.Client.handle(Client.java:153)
at org.restlet.Restlet.handle(Restlet.java:275)
at org.apache.camel.component.restlet.RestletProducer.process(RestletProducer.java:79)
at org.apache.camel.component.restlet.RestletProducer.process(RestletProducer.java:98)
at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:141)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:460)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:190)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:121)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:83)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:460)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:190)
at org.apache.camel.processor.MulticastProcessor.doProcessSequential(MulticastProcessor.java:668)
at org.apache.camel.processor.MulticastProcessor.doProcessSequential(MulticastProcessor.java:596)
at org.apache.camel.processor.MulticastProcessor.process(MulticastProcessor.java:237)
at org.apache.camel.processor.Splitter.process(Splitter.java:104)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:460)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:190)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:121)
at org.apache.camel.processor.Pipeline.process(Pipeline.java:83)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:190)
at org.apache.camel.component.direct.DirectProducer.process(DirectProducer.java:62)
at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:141)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:190)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:460)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:190)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:109)
at org.apache.camel.processor.MulticastProcessor.doProcessParallel(MulticastProcessor.java:814)
at org.apache.camel.processor.MulticastProcessor.access$200(MulticastProcessor.java:84)
at org.apache.camel.processor.MulticastProcessor$1.call(MulticastProcessor.java:314)
at org.apache.camel.processor.MulticastProcessor$1.call(MulticastProcessor.java:299)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
And as per the doc I did configure the restlet component with the following code but I'm still seeing the same issue:
#Bean
public RestletComponent restlet()
{
RestletComponent restlet = new RestletComponent();
restlet.setMaxThreads(100);
restlet.setThreadMaxIdleTimeMs(10000);
restlet.setMaxQueued(20);
return restlet;
}
Note: The route did accepted 10 requests at a time then I started getting errors. And from configuration I could see the maxThreads by default is 10. Which means the that I did through Bean is not picking up properly.
Actually in my code I have defined restlet bean after route configure i.e as below
public class RoutesBuilder extends FatJarRouter {
....
#Override
public void configure() throws JAXBException {
......
}
#Bean(name={"restlet"})
public RestletComponent restlet()
{
.......
}
}
And now I have changed the order of defining the code as i.e first I have defined restlet and the route configure as below. With that in place I saw the restlet configuration is been picked up and I no more see the connection pool issue.
public class RoutesBuilder extends FatJarRouter {
....
#Bean(name={"restlet"})
public RestletComponent restlet()
{
.......
}
#Override
public void configure() throws JAXBException {
......
}
}
Check these things:
Make sure you have enabled <context:annotation-config/> in the Spring App Context XML file.
Use <context:component-scan base-package="<your package>" /> in the Spring XML.
Make sure you have annotated the containing that #Bean with #Configuration.
Add the name attribute to the #Bean: #Bean(name={"restlet"}).
Hope that helps.
Take a look at this example. Its Spring-boot APP. I created a separate config class and used spring-boot configuration annotation, so on startup spring-boot does all the configuration needed
Here is a working solution
https://github.com/RakeshBhat/rb-springbootcamelrestlet

Spring Boot app with Eureka DiscoveryClient fails to start

I'm trying to write a simple Spring Boot application that can (1) register with a Netflix Eureka server, and (2) query the Eureka server to retrieve details of other registered services.
My client class has an #Autowired field of type com.netflix.discovery.DiscoveryClient that is used to talk to Eureka and query it to learn about other services. On my main class I have the annotation #EnableDiscoveryClient:
#SpringBootApplication
#EnableDiscoveryClient
public class AppBootstrap {
public static void main(String[] args) {
SpringApplication.run(AppBootstrap.class, args);
}
}
In my application.yml file under src/main/resources I have:
eureka:
instance:
lease-renewal-interval-in-seconds: 10
lease-expiration-duration-in-seconds: 20
prefer-ip-address: true
secure-port: 443
non-secure-port: 80
metadata-map:
instanceId: my-test-instance
client:
service-url:
defaultZone: http://localhost:9080/eureka/
registry-fetch-interval-seconds: 6
instance-info-replication-interval-seconds: 6
register-with-eureka: true
fetch-registry: true
heartbeat-executor-thread-pool-size: 5
eureka-service-url-poll-interval-seconds: 10
When I start my app the service fails to boot, throwing an exception that is rooted at:
Caused by: java.lang.AbstractMethodError: org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean.getInstanceI
d()Ljava/lang/String;
at com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider.get(EurekaConfigBasedInstanceInfoProvider
.java:53)
at com.netflix.appinfo.ApplicationInfoManager.initComponent(ApplicationInfoManager.java:90)
... 25 more
I've no idea what's going on here. Any ideas? I believe the app should still start even if my Eureka config is incorrect, but it falls over at start time.
Secondly, am I using the correct DiscoveryClient? Ideally I'd like to make it general such that I could use it with Eureka, Consul or ZooKeeper as examples. I find the documentation isn't great at illucidating exactly what's required when using these Spring Cloud / Netflix discovery components.
You can use
org.springframework.cloud.client.discovery.DiscoveryClient
then you can get the list of instances with discoveryClient.getInstances
ServiceInstance instance = discoveryClient.getInstances(service).get(0);
instance.getUri().toString();
If you use another components like RestTemplate, Ribbon, etc you only need to use the name of the service (name registered in eureka) in the URL
restTemplate.getForObject("http://PRODUCTSMICROSERVICE/products/{id}", Product.class, id)
You can see more here
https://spring.io/blog/2015/01/20/microservice-registration-and-discovery-with-spring-cloud-and-netflix-s-eureka
I received the autowiring error in my experience when i was using discoveryclient to get the information in the class outside any function. So I was using eureka to find out the port for my service as the port was described as 0 hence service was picking up port dynamically while starting as spring boot application. I needed to know the port programmatically . In the controller i used the code like below in wrong way
public class HelloController {
private static final Logger LOG = LoggerFactory.getLogger(HelloController.class);
#Autowired
private DiscoveryClient discoveryClient;
int port = discoveryClient.getLocalServiceInstance().getPort();
#RequestMapping("/hello/{id}")
public String sayhello(#PathVariable String id)
{
String s ="A very nice and warm welcome to the world "+id;
LOG.info(String.format("calling helloservice for %s",id));
LOG.info(String.format("calling helloservice for port %d",port));
return s;
}
Once i put the port code inside the sayhello method the error went away. So the correct way of retreiving the port is as below
public class HelloController {
private static final Logger LOG = LoggerFactory.getLogger(HelloController.class);
#Autowired
private DiscoveryClient discoveryClient;
#RequestMapping("/hello/{id}")
public String sayhello(#PathVariable String id)
{
String s ="A very nice and warm welcome to the world "+id;
int port = discoveryClient.getLocalServiceInstance().getPort();
LOG.info(String.format("calling helloservice for %s",id));
LOG.info(String.format("calling helloservice for port %d",port));
return s;
}
If we are using the latest versions of Spring Boot then we wouldn't require the #EnableDiscoveryClient or #EnableEurekaClient to be defined in the main class. This happens in the background by Spring when we add the dependencies in pom.xml
Please make sure your files have the below basic informations.
pom.xml
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>2020.0.0-SNAPSHOT</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
application.properties or YAML file as per choice
spring.application.name=eureka-client
eureka.client.service-url.defaultZone: ${EUREKA_URI:http://localhost:8761/eureka}
eureka.instance.prefer-ip-address= true
server.port= 8082
No changes or # Annotations required in the main class in Application.java
Please checkout my GIT Repository here for the working code.
add application.yml file these settings;
Our product application run at this port
server :
port : 8482
Our service will be register by own service name
spring :
application :
name : product-service
# To be register we assign eureka service url
eureka:
client:
service-url :
defaultZone:
${EUREKA_URI:http://localhost:8481/eureka} # add your port where your eureka server running
instance :
prefer-ip-address : true
# Logging file path
logging :
file :
path : target/${spring.application.name}.log

Categories