Netflix Eureka Server And Client Setup With Spring Boot

Netflix Eureka Server Setup

Overview

  • We will set up a Eureka server (service registry used to register multiple services/microservices).
  • We will set up multiple Eureka clients(REST services that register to Eureka Server).
  • We will do client-side load balancing and service discovery through Eureka.

Setting up Eureka Server

The dependency required to set up a eureka server is “spring-cloud-starter-netflix-eureka-client” along with spring-boot-starter-parent. you can generate the code by going to https://start.spring.io/ , and provide the group id, artifact id and provide the required dependencies as shown below, and click on generate which will generate the sample code with dependency added to your pom.xml



The corresponding pom.xml should look like the below

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>eurekaserver</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>eurekaserver</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
		<spring-cloud.version>Hoxton.SR1</spring-cloud.version>
	</properties>

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

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<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>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Once you have the project open the main Springboot Class with annotation @SpringbootApplication and add the annotation @EnableEurekaServer, the class should look like this.

package com.example.eurekaserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaserverApplication {

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

}

The last step in setting up the server is adding the application.yml file which will have eureka relate properties when you start the application with @EnableEurekaServer annotation it will look for bootstrap.yml file if not found it will look for application.yml file for the properties the yml file should look something like this.

server:
  port: 9090

eureka:
  client:
    register-with-eureka: false
    fetch-registry: false
    serviceUrl:
      defaultZone: http://localhost:9090/eureka/

The above properties yaml file defines the eureka defaultZone serviceUrl where eureka is supposed to run. register-with-eureka property is set to false as we don’t want to register Eureka Server to itself.
Once everything is the project structure should look like the below image

Go ahead and start the spring boot application, the eureka server should be up in whatever port you mentioned in application.yml file in this case eureka server will be up at localhost:9090 and will look like below.

Ola, we have set up the eureka server.

Now we will go ahead and create two clients named client1 and client2 from the spring initializer like the above with adding one more dependency Eureka Discovery Client, as shown below

Once we have both the projects created we will go ahead and add the annotation @EnableDiscoveryClient on the root SprintBootApplication class as shown below for both the clients Client1 and Client2

package com.example.client2;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class Client2Application {

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

}

Similarly, we need to update the application.yml file as below providing the required eureka config details.

spring:
  application:
    name: 'client1'
server:
  port: 8081

eureka:
  instance:
    hostname: ${vcap.application.uris[0]:localhost}
    prefer-ip-address: true
    lease-renewal-interval-in-seconds: 10
    lease-expiration-duration-in-seconds: 20
  client:
    service-url:
      defaultZone: http://localhost:9090/eureka
    

In the above code, we have provided the spring application name and eureka client service URL where the eureka server resides, so once you start the client it will look into the service URL and tries to register itself. The property lease-renewal-interval-in-seconds: 10 & lease-expiration-duration-in-seconds: 20 lets the Eureka Server when to check for the health of the client. Once you made these changes go ahead and start both the clients.

If you go back to Eureka Server you will now be able to see the two clients registered with names CLIENT1 and CLIENT2 as shown below.

Now the setup has been completed the two clients can talk to each with using the service discovery.

Here is the video tutorial explaining the same

Java Datatypes

What is a Datatype?
A data type is an attribute of data that tells the compiler or interpreter how the programmer intends to use the data.

Data types in Java programming language

There are two different sets of data types in Java

  • Primitive Datatypes
  • Non Primitive Datatypes

The below image depicts different data types in java

Java Datatypes

The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. This involves stating the variable’s type and name.

boolean: is used to store true or false value.

byte, short, int, long: is used to store whole numbers.

float, double: is used to store fractional numbers.

The below table depicts different datatypes and the size of those datatypes.

package com.test.java;

public class BasicDataTypes {
	
	static byte i = 127;
	static short j = 3456;
	static int k = 24233534;
	static long l = 34564;
	static float fl = 35325432;
	static double db = 34523763;
	static boolean b = true;
	static char c = 'c';
	
	static String testString = "Hello World";
	
	
	public static void main(String [] args) {
		char[] testCharString = new char[11];
		testCharString[0] = 'h';
		testCharString[1] = 'e';
		testCharString[2] = 'l';
		testCharString[3] = 'l';
		testCharString[4] = 'o';
		testCharString[5] = ' ';
		testCharString[6] = 'w';
		testCharString[7] = 'o';
		testCharString[8] = 'r';
		testCharString[9] = 'l';
		testCharString[10] = 'd';
		
		System.out.println("Default value of byte is ---> "+i);
		System.out.println("Default value of short is ---> "+j);
		System.out.println("Default value of int is ---> "+k);
		System.out.println("Default value of long is ---> "+l);
		System.out.println("Default value of float is ---> "+fl);
		System.out.println("Default value of double is ---> "+db);
		System.out.println("Default value of boolean is ---> "+b);
		System.out.println("Default value of char is ---> "+c);
		System.out.println("Default value of String is ---> "+testString);
		System.out.println("Default value of char is ---> "+String.valueOf(testCharString));

		
	}

}

Here is the video

Difference between JDK, JRE, and JVM

In this post, we will see the major differences between JDK, JRE, and JVM.

JDK (Java Development Kit): JDK is the one you need to build applications in Java, it contains everything that is required to build and run Java applications. When you download java from the oracle site to develop applications you actually download JDK, which comes with JRE and the following Devtools,

JavaC: Java Compiler which compiles your Java code.
Java: Interpreter/loader which reads your java code.
JavaDoc: This helps in generating java documentation for your code.

JRE (Java Runtime Environment): JRE contains everything to run the java application, it contains code libraries required to develop java applications. JRE contains the Java class libraries, the Java class loader, and the Java Virtual Machine. In this system:
The class loader is responsible for correctly loading classes and connecting them with the core Java class libraries. The JVM is responsible is to ensure Java applications have the resources they need to run and perform well in your device or cloud environment.
The JRE is an orchestrator between these components.

JVM (Java Virtual Machine): JVM is machine-specific and can only read byte code that has been generated using java compiler.  Once the java compiler compiles the code to byte code, JVM is the one which reads it and runs on that machine, you might have heard that Java is portable, this is what it meant the compiled byte code can be run on any machine with the help of JVM.

Java Conceptual Diagram
Image Courtesy Oracle.com

You might have seen the below image saying Java is being run on 3 billion devices, it actually means JVM is running.

3 Billion devices run java

Here is the basic intro to Java Programming Language.

Google Firebase Tutorial Beginners.

In this tutorial will see how to connect to Firebase Firestore Database and persist data using rest web services.

For this will start from the rest web service that we built using spring boot in the previous blog post Build Restful web service using Spring boot and Java.

If you are a video guy here is the video which demonstrates connecting to Firebase and persists data

Go to firebase.google.com and click on the got to console on the top right corner, it will take you to the console as shown below. Click on Add project and give it a name.

Firebase Console

Once created it will take you to your project console page as shown below, click on the database and create a collection named “users”.

Once created the collection, we will go to project settings -> service Accounts tab to generate the key and save it in your project, that we will use to connect to the firebase firestore database. We will also grab the admin SDK configuration snippet for java.

Now open the pom.xml and add the google firebase admin SDK dependency

<dependency>
    <groupId>com.google.firebase</groupId>
    <artifactId>firebase-admin</artifactId>
    <version>6.11.0</version>
</dependency>

Add a file named FirebaseInitialize which we will use to make a connection to firebase during the application startup. The class looks like this.

package com.example.demo.service;

import java.io.FileInputStream;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Service;
import com.google.auth.oauth2.GoogleCredentials;

import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;

@Service
public class FirebaseInitialize {
	
	@PostConstruct
	public void initialize() {
		try {
		FileInputStream serviceAccount =
				  new FileInputStream("./serviceAccount.json");

				FirebaseOptions options = new FirebaseOptions.Builder()
				  .setCredentials(GoogleCredentials.fromStream(serviceAccount))
				  .setDatabaseUrl("https://fir-demo-8920f.firebaseio.com")
				  .build();

				FirebaseApp.initializeApp(options);
	} catch (Exception e) {
		e.printStackTrace();
	}

}
}

@Service Annotation lets the spring bootup know that it is a service class and needs to be bound.
@PostConstruct Annotation specifies that the function initialize() should run before the launch of the application, so it creates a firebase connection.
We have the code that we copied from the firebase console in the earlier step pasted here.
The first line reads the serviceAccount.json which we generated on the firebase project settings page from step 1.
It connects to firebase with FirebaseApp.initializeApp using the options build using FirebaseOptionsBuilder which will have credentials that we extracted from serviceAccount.json and the databaseURL.

We will now write a Firebase Service class which will have four functions to do crud operations, createUser (to create new User), updateUser (to update existing User), getUserDetails(to retrieve user details), deleteUser (to delete existing User) the class looks like below.

package com.example.demo.service;

import java.util.concurrent.ExecutionException;

import org.springframework.stereotype.Service;

import com.example.demo.objects.Person;
import com.google.api.core.ApiFuture;
import com.google.cloud.firestore.DocumentReference;
import com.google.cloud.firestore.DocumentSnapshot;
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.WriteResult;
import com.google.firebase.cloud.FirestoreClient;

@Service
public class FirebaseService {
	
	public String saveUserDetails(Person person) throws InterruptedException, ExecutionException {
		Firestore dbFirestore = FirestoreClient.getFirestore();
		ApiFuture<WriteResult> collectionsApiFuture = dbFirestore.collection("users").document(person.getName()).set(person);
		return collectionsApiFuture.get().getUpdateTime().toString();
	}
	
	public Person getUserDetails(String name) throws InterruptedException, ExecutionException {
		Firestore dbFirestore = FirestoreClient.getFirestore();
		DocumentReference documentReference = dbFirestore.collection("users").document(name);
		ApiFuture<DocumentSnapshot> future = documentReference.get();
		
		DocumentSnapshot document = future.get();
		
		Person person = null;
		
		if(document.exists()) {
			person = document.toObject(Person.class);
			return person;
		}else {
			return null;
		}
	}
	
	public String updateUserDetails(Person person) throws InterruptedException, ExecutionException {
		Firestore dbFirestore = FirestoreClient.getFirestore();
		ApiFuture<WriteResult> collectionsApiFuture = dbFirestore.collection("users").document(person.getName()).set(person);
		return collectionsApiFuture.get().getUpdateTime().toString();
	}
	
	public String deleteUser(String name) {
		Firestore dbFirestore = FirestoreClient.getFirestore();
		ApiFuture<WriteResult> writeResult = dbFirestore.collection("users").document(name).delete();
		return "Document with ID "+name+" has been deleted";
	}
}

We will have this class also defined with @Service annotation so it will be available for auto wiring.
Since having the connection to the database initialized earlier we will extract the DB here to perform operations on that.
Firestore dbFirestore = FirestoreClient.getFirestore();
this will instantiate the firestore client object which we will use to access the collections we created.
ApiFuture collectionsApiFuture = dbFirestore.collection(“users”).document(person.getName()).set(person)
this line of syntax gets the collection “users” and tries to document with id (In our case i’m setting the id as the users name), if it didn’t find the document with specified id it will create the new document with Person object .
If there is an id already exists it will update the document, if you observer the function updateUser it will have the same logic as createUser.

If you have a problem following the tutorial, here is the video which demonstrates the complete tutorial.

Build A RESTful Web Service Using Java And Spring Boot

In this following tutorial, we will build a simple REST web service using java with spring boot.

What is a Web Service?
Web Service is a standard or common way of communication between a client and a server.

Restful Web Services, Web Service

The above diagram shows the pictorial representation of a web service call, the clients a computer, or a phone are basically clients, when you try to perform open facebook app your mobile phone app, it sends a web service request (Http Request) to get the data to show on your feed.


There are in general two kinds of web services in usage

  • SOAP (Simple Object Access Protocol).
  • REST (REpresentational State Transfer).

SOAP: SOAP as the name says it’s an access protocol to make requests and receive responses based on a protocol that will be defined between the client and the server.
There are many caveats of using SOAP one of it is you can only transfer and receive XML data when using a SOAP web service. Hence restful web services came into existence.

REST: Rest as the name says its a state of transferring data between clients and servers, there are no set protocols attached to it, you can send any kind of data, XML, JSON, TEXT, FILE format data using REST web services, in most cases, you will be using JSON format.

SPRING BOOT makes it so much easier to build REST web services from the ground up, it provides a lot of configuration inbuilt so that you can build web services/ microservices rapidly, it also provides inbuilt tomcat server which removes the hassle of having a server install in and deploy your JAR/WAR file like the old times, we will see how to build the rest web service using Spring boot, Java and maven build tool.

Using the spring tool suite we can create a sample spring boot project as shown in the below image. Go to File -> New -> Other Project and select Spring boot-> Spring boot Starter project it will create you a default spring boot project.

Spring tool suite create spring boot project.

Follow the steps and you will have your demo application created and you should be able to see a java file named DemoApplication.java (Demo is the name of the project) which will look something like this.

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

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

}

@SpringBootApplication annotation takes care of three annotations combined
@Configuration: Tags the class as a source of bean definitions for the application context.
@EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. For example, if spring-webmvc is on the classpath, this annotation flags the application as a web application.
@ComponentScan: Tells Spring to look for other components, configurations, and services in the base package in our case com.example.demo letting it find the controllers.

If you never use Spring MVC you might have not known of these annotations. Spring boot starter project also creates a POM.XML like below which will have all the required dependencies except spring-boot-starter-web dependency which we need to add for creating Rest web service.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Now we will go ahead and create a controller class that will have our REST endpoints, which will look something like below.

package com.example.demo.controller;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.object.Person;

@RestController
public class UserController {
	
	@GetMapping("/getUserDetails")
	public String getUserDetails(@RequestHeader String name) {
		return "Requesting Details of User"+name;
	}
	
	@PostMapping("/createUser")
	public String createNewUser(@RequestBody Person person) {
		return "Created new User "+person.getName();
	}
	
	@PutMapping("/updateUser")
	public String updateUser(@RequestBody Person person) {
		return "Updated user "+person.getName();
	}
	
	@DeleteMapping("/deleteUser")
	public String deleteUser(@RequestBody Person person) {
		return "Deleted User "+person.getName();
	}

}

HTTP Methods: There are four main HTTP methods that we use in common for web service calls they are

  • GET (used to retrieve existing data).
  • POST (used to create/insert new data).
  • PUT (used to update existing data).
  • DELETE (used to delete data).

We have implemented all these methods in the above UserController class.
@RestController lets the spring boot application that this class is a controller class having rest endpoints so that spring configures this class to its HTTP routes.
@GetMapping, having this annotation makes the corresponding method is called when a get call is made to the endpoint /getUserDetails.
Similarly @PostMapping, @PutMapping, @DeleteMapping calls the corresponding methods/functions when those methods are used.
@RequestHeader captures the data sent in the header parameters and @RequestBody captures the data sent in the body of the Rest Call.

That is all you need to bring up the service, set up the run configurations in STS or whichever IDE you might be using pointing to the DemoApplication.java class as the main class, it boots up the spring application using inbuilt tomcat and your services will be available on PORT 8080 by default.

You can follow through this video if you need any help in getting it up and running

Restful Web Services Tutorial.