Service discovery with Eureka

Eureka is REST based application service, That primarily used for service register and middle-tier api load balancing.

Why Eureka required ?

There is many reason where we can consider eureka
– Service registry
– Client side load balancing
– Peer to peer connectivity between server
– Maintain self preservation state in case network collapse at certain threshold
– Scope of customisation
– Mid-tier load balancing

How Eureka work?

Eureka come up with two components. Eureka client and Eureka server. Any application who doing service discovery on Eureka server should have Eureka client enabled. actually if we complete server setup there is three application that came into picture –

  • Eureka server – that hold the client details and do mid-tier load balancing
  • Application client – That is Eureka client that called to other services.
  • Application services – That is also Eureka client but called by other services.

Let’s understand with example – Suppose we have web-application that have two services. one web client that hold front end implementation. and other backend services that hold business logics. here both backend and frontend is kind of client for Eureka server and both add eureka client component so they can send their heart bit to eureka server. and In this scenarios eureka server maintain registry of both application(web client and backend services). also web client not required to directly called to backend services. that can call to eureka server. where eureka server redirect their call to specific instance as per availability. Here Eureka server use Round-Robin algorithm to redirect request of client.

Eureka server client communication and stats ?

Register – Eureka client registers the information about the running instance to the Eureka server.
Renew – Eureka client needs to renew the lease by sending heartbeats every 30 seconds. The renewal informs the Eureka server that the instance is still alive. If the server hasn’t seen a renewal for 90 seconds, it removes the instance out of its registry. It is advisable not to change the renewal interval since the server uses that information to determine if there is a wide spread problem with the client to server communication.
Fetch registry – Eureka clients fetches the registry information from the server and caches it locally. After that, the clients use that information to find other services
Cancel – Eureka client sends a cancel request to Eureka server on shutdown. This removes the instance from the server’s instance registry thereby effectively taking the instance out of traffic.
Time lag– All operations from Eureka client may take some time to reflect in the Eureka servers and subsequently in other Eureka clients. This is because of the caching of the payload on the eureka server which is refreshed periodically to reflect new information. Eureka clients also fetch deltas periodically. Hence, it may take up to 2 mins for changes to propagate to all Eureka clients.

Let’s go through example ,
Here i’m going create these applications.
1. Eureka server – that will register all the services.
2. Application Service – This will backend application called by client but its also registered with Eureka as client
3. Application Client – this will be client application that Called Application services via eureka server.

Eureka Server

I would suggest you to visit – Spring initialiser and generate Spring application from there and don’t forget to include Eureka server dependencies. for more details please visit this page to know more details.

Once you imported the project into your IDE. then go to resource folder and open application.properties/yml files. defined below bare minimum properties to make your server up and visible.

//YAML format
server:
    port: 8761

eureka:
    instance:
        hostname: localhost
    client:
        fetch-registry: false
        register-with-eureka: false
        serviceUrl:
            defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
spring:
    freemarker:
        prefer-file-system-access: false
        template-loader-path: classpath:/templates/
-------------------------------------------------------------------------
OR
// properties format

eureka.instance.hostname=localhost
eureka.client.fetch-registry=false
eureka.client.register-with-eureka=false
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
server.port=8761
spring.freemarker.prefer-file-system-access=false
spring.freemarker.template-loader-path=classpath:/templates/

server.port – Server port details, Here we require to define unique port no.
eureka.client.fetch-registry – mark this as false so it will not try to fetch registry details as client
eureka.client.register-with-eureka – So it will not register them self
eureka.client.serviceUrl.defaultZone – Define default zone address for the client, so client connect at this address
spring.freemarker.template-loader-path – as UI page is by default included with Eureka server. so pointed template path in class path incase if by default not detected
spring.freemarker.prefer-file-system-access – there is no need to read local file system.

Now open application.java files and enable Eureka server using @EnableEurekaServer annotation.Then start server

@EnableEurekaServer
@SpringBootApplication
public class EurekaserverApplication {

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

Once server up, now visit on this link – http://localhost:8761, you will see similar dashboard as below,

Eureka dashboard

Here there is no application registered with Eureka server now. Lets create Eureka Client.

Eureka Client

Same as Eureka server we require to generate project from Spring Initialiser , Once project generated and open into IDE, we require to edit application.properties/yml file.

spring:
  application:
    name: eureka-service-client

server:
  port: 8082

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka
---------------------------------------------------------------------
OR
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka
server.port=8082
spring.application.name=eureka-service-client

eureka.client.serviceUrl.defaultZone – Default zone for eureka client to register
server.port – server port
spring.application.name – named the application the same will be visible to eureka server

Open application.java files and @EnableDiscoveryClient.

@SpringBootApplication
@EnableDiscoveryClient
public class EurekaclientApplication {

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

}

Now start the client server and check on Eureka if they are visible.

Advertisement
Featured

Generate Spring project base template in Java/Kotlin/Groovy

There is various way we can generate REST application base template in java. Today I’m going to share you one of the example.

Why we require to generate the template ?

Going with your own project structure is good for example or test project. but if we talking about production application or some of serious project we must require to follow the standard. generally if we talk about Framework like spring that have certain rules to read application properties and they have defined standard project structure. and that is very use-full and self explanatory.

you can see on of this example, where clearly defined ‘src’ section that contain test and main application source. apart from this there is HELP.md where user can define there application details. also there is gradle config files are there that can be replace with maven if you choose maven build system.


├── HELP.md
├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── example
    │   │           └── demo
    │   │               └── DemoApplication.java
    │   └── resources
    │       └── application.properties
    └── test
        └── java
            └── com
                └── example
                    └── demo
                        └── DemoApplicationTests.java

Now these are The basics template every time create these structure manually is not worth to spend time. if there is already tools out there.
Spring introduced spring initialiser that can help you generate base template where developer only require to generate and import into IDE.

How to do this?

visit – https://start.spring.io/

Hope you like this 🙂

Install spring boot application on linux

Today most of the people prefer to deploy the standalone application and easy to manageable instead of doing too much overhead or get expert advice on it to manage a specific web server for rest application.

dilemma: When we have a standalone jar there are few minor hacks we have to do this with it. like, configure log path, start with a specific promised user. run it with standalone process instead of inline execution.

A fully executable jar can be executed like any other executable binary or it can be registered with ‘systemd‘.  This makes it very easy to install and manage spring boot applications in common production environments.

#systemd: systemd is system and service manager for linux operating system. When run as the first process on boot (as PID 1), it acts as init system that brings up and maintains userspace services. it is a replacement of ‘Unix system v’ and BSD (Berkeley Software Distribution) init system. for more detail #man systemd

Assume that you have a linux server that has Java installed, now place your executable spring boot jar file in a /opt/apps/ directory

Now create a app.service file in a /etc/systemd/system
directory and execute below command also make sure your permission before creating a file at a particular location
#vi /etc/systemd/system/app.service

and paste script

[Unit]
Description=sample application
After=syslog.target

[Service]
User=appUser
ExecStart=/opt/apps/app.jar
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target

now save above script using “:wq” for more detail check vi editor helps(#man vi)

let’s enable service

#systemctl enable app.service
(check #man systemctl for more detail.)

once service enables now you can start, stop and check status of your service.

#systemctl start app.service
#systemctl stop app.service

Hope you like this. Thanks for reading 🙂

Expose RESTful APIs using spring boot in 7 minutes

Hello Friends,

Today we are going to see how to expose standalone RESTful web services, the purpose of a post is to enable a reader to write their own restful web services.

Yes, that’s right! , I’m sure if you see complete video of this post you can write your RESTful web service.. ok enough talk 🙂 let’s start.

 

Hope you like this post. Thanks 🙂

 

 

Create spring beans using YAML

Spring highly adopted annotation based configuration and it is happily accepted by developer communities and why not, no one wants to struggle with XML tags but that’s not enough somewhere we still miss XML configuration or you can say external file configuration as powerful as XML configuration. especially when we write an application that has to alter behaviors without compilation.

But still writing an XML configuration is not readable and not easily understandable for beginners, so I’ve written experimental plugins for spring boot that convert YAML definition to Spring Beans.

here is an example of bean definition in XML and same in YAML.

Spring-beans.xml

Screen Shot 2017-11-04 at 6.45.07 PM

Spring-beans.yaml

Screen Shot 2017-11-04 at 6.44.14 PM

above code snippet, you can see a line of code and readability, let jump in a code example.

below code snippet, only need to add annotation “@ImportYamlResource” that will work same as “@ImportResource”

Screen Shot 2017-11-05 at 10.38.22 AM

below an example link, you can check out a project from git

yaml-beans-example

download library 

 

Note ->  YAML-spring-beans is a just experimental library, still there are lots of features not included

feedback will be much appreciated 🙂