Blog Microservices Implementation in Java RSS Feed

Microservices Implementation in Java

Feb 27, 2018

Microservices is a synonym for Service Oriented Architectural (SOA) style of constructing aggregation of many small loosely coupled services. When developing microservices with java, you can use several microservices framework. Some of the frameworks are Spring Boot, Jersey, Dropwizard, Play Framework, and Restlet. In this document, we will implement a microservice “authenticate” with Spring Boot. Spring Boot is the best and most used Microservice framework since long.

Microservices in JAVA

The advantage of Spring Boot is that it has a vast infrastructure and has many spring projects working along. To create microservices with Spring Boot, you need to follow below mentioned 3 steps:

  • Setup new service
  • Expose the resource using RestController
  • Consume the service resource with RestTemplate

Here, we are going to create 3 different microservices. First microservice is Discovery Server which is a Eureka server. Second microservice is Authentication Service which is Producer service and Third microservice is Consumer service which is discovery client. This microservice can find other microservices using its RestTemplate. Let’s start with developing these three microservices.

Developing Discovery Server

Service Discovery is used so that microservices can find each other. We use Eureka for our service discovery. Eureka, created by Netflix, provides service discovery with Spring Cloud. Folder Structure for Discovery server is as below: folder structure Maven Dependency:

<parent>
	<groupid>org.springframework.boot</groupid>
	<artifactid>spring-boot-starter-parent</artifactid>
	<version>1.5.3.RELEASE</version>
</parent>
<dependencies>
	<dependency>
		<groupid>org.springframework.cloud</groupid>
		<artifactid>spring-cloud-starter</artifactid>
	</dependency>
	<dependency> <!-- Eureka registration server -->
		<groupid>org.springframework.cloud</groupid>
		<artifactid>spring-cloud-starter-eureka-server</artifactid>
	</dependency>
	<dependency>
		<groupid>org.springframework.boot</groupid>
		<artifactid>spring-boot-starter-web</artifactid>
	</dependency>
</dependencies>
<dependencymanagement>
	<dependencies>
		<dependency>
			<groupid>org.springframework.cloud</groupid>
			<artifactid>spring-cloud-dependencies</artifactid>
			<version>Camden.SR5</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencymanagement>

Application.yml:

eureka: # Configure this Discovery Server
	instance:
		hostname: localhost
	client: 
		registerWithEureka: false
		fetchRegistry: false
server: # HTTP (Tomcat) port
	port: 9000

To run Eureka registry service is easy, just define @EnableEurekaServer annotation to spring boot application.

@SpringBootApplication
@EnableEurekaServer
public class DiscoveryServerApplication {
	public static void main(String[] args) {
		SpringApplication.run(DiscoveryServerApplication.class, args);
	}
}

After running this microservice, following output is available on localhost:9000: tsblog Here in the application section of the image, there is no instance currently available with Eureka. After running Producer and Consumer microservice, we will able to see the instances in the Application section.

Developing Authentication Service

In this, we will create Login and Registration methods. We will use Spring Data JPA for querying MySQL database using method name convention. You can learn spring data JPA from this site: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/. Also in this, we will be hashing the password using Spring Security’s BCrypt algorithm. Folder Structure for Authentication service is as below: tsblog2 Maven Dependency:

<dependencies>
	<dependency>
		<groupid>org.springframework.cloud</groupid>
		<artifactid>spring-cloud-starter</artifactid>
	</dependency>
	<dependency>
		<groupid>org.springframework.cloud</groupid>
		<artifactid>spring-cloud-starter-eureka</artifactid>
	</dependency>
	<dependency>
		<groupid>org.springframework.boot</groupid>
		<artifactid>spring-boot-starter-web</artifactid>
	</dependency>
	<dependency>
		<groupid>org.springframework.boot</groupid>
		<artifactid>spring-boot-starter-data-jpa</artifactid>
	</dependency>
	<dependency>
		<groupid>mysql</groupid>
		<artifactid>mysql-connector-java</artifactid>
	</dependency>
</dependencies>

Application.yml:

spring: # Service registers under this name
	application:
		name: authentication-service
	datasource: # MySql credentials
		url: jdbc:mysql://127.0.0.1:3306/test
		username: root
		password: root
	jpa: # JPA support
		show-sql: true
		hibernate:
			ddl-auto: validate
			use-new-id-generator-mappings: false
		properties:
			hibernate:
			dialect: org.hibernate.dialect.MySQLDialect
eureka: # Discovery Server Access
	client:
		serviceUrl:
			defaultZone: http://localhost:9000/eureka/
server: # HTTP Server (Tomcat) Port
	port: 9001

To define this microservice as Discovery Client, we need to include @EnableDiscoveryClient annotation to application.

@SpringBootApplication
@EnableDiscoveryClient
public class AuthenticationClientApplication {
	public static void main(String[] args) {
		SpringApplication.run(AuthenticationClientApplication.class, args);
	}
}

We will create AuthenticationRepository to querying the database using JPA. To expose Authentication service, we use RestController. In the controller, @CrossOrigin annotation is used to pass data or get data from cross platforms like Angular.

@RestController
@CrossOrigin
public class AuthenticationController {
	@Autowired
	private AuthenticationRepository repo;
	@RequestMapping(&quot;/api/getUsers&quot;)
	public @ResponseBody List<userauthenticationbean> getUsers() {
		return repo.findAll();
	}
	@RequestMapping(value = &quot;/api/addUser&quot;,method = RequestMethod.POST)
	public @ResponseBody UserAuthenticationBean addStudent(@RequestBody UserAuthenticationBean user) {	// Hashing the password using BCrypt of Spring Security 
		String hashed_password = BCrypt.hashpw( user.getPassword(), BCrypt.gensalt(12) ); 
		UserAuthenticationBean newuser = new UserAuthenticationBean();
		newuser.setUserName(user.getUserName());
		newuser.setPassword(hashed_password);
		return repo.save(newuser);
	}
	@RequestMapping(value = &quot;/api/getUser&quot; ,method = RequestMethod.POST)
	public @ResponseBody UserAuthenticationBean getByUser(@RequestBody UserAuthenticationBean user) {
		UserAuthenticationBean userget = repo.findByUserName(user.getUserName());
		// Comparing Hashed password with given password
		If ( BCrypt.checkpw( user.getPassword(), userget.getPassword() ) ){
			return userget;
		} return null;
	} 
}
</userauthenticationbean>

After running this microservice, you can fire rest call to this service on localhost:9001. Also, instance of this service gets registered in eureka server which is already running on localhost:9000.

Developing Consumer Service

In this service, we will use RestTemplate to consume the remote service resource. Also we use Spring Cloud’s Netflix support for load balancing. Load balancing is used to decide which service instance to use. Netflix Ribbon provides several algorithms for client-side load balancing. Folder Structure for Consumer service is as below: tsblog3 Maven Dependency:

<dependencies>
	<dependency>
		<groupid>org.springframework.cloud</groupid>
		<artifactid>spring-cloud-starter-eureka</artifactid>
	</dependency>
	<dependency> <!-- Netflix Ribbon used for Load Balancing -->
		<groupid>org.springframework.cloud</groupid>
		<artifactid>spring-cloud-starter-ribbon</artifactid>
	</dependency>
	<dependency>
		<groupid>org.springframework.boot</groupid>
		<artifactid>spring-boot-starter-web</artifactid>
	</dependency>
</dependencies>

Application.yml:

spring: # Service registers under this name
	application:
		name: consumer-service
eureka: # Discovery Server Access
	client:
		serviceUrl:
			defaultZone: http://localhost:9000/eureka/
server: # HTTP Server (Tomcat) Port
	port: 8081

You need to include RemoteRepository bean and RestTemplate bean in main application, so that this microservice can consume other microservices.

@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerServiceApplication {
 
	public static final String AUTHENTICATION_SERVICE_URL = &quot;http://AUTHENTICATION-SERVICE&quot;;
 
	public static void main(String[] args) {
		SpringApplication.run(ConsumerServiceApplication.class, args);
	}
 
	@Bean
	@LoadBalanced
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}
 
	@Bean
	public AuthenticationRepository authenticationRepository(){
		return new RemoteAuthenticationRepository(AUTHENTICATION_SERVICE_URL);
	}
}

RemoteRepository will pass the HTTP request to the given Service URL and get the response from the remote service.

public class RemoteAuthenticationRepository implements AuthenticationRepository {
	@Autowired
	@LoadBalanced
	protected RestTemplate restTemplate;
	protected String serviceUrl;
 
	public RemoteAuthenticationRepository(String serviceUrl) {
		this.serviceUrl = serviceUrl.startsWith(&quot;http&quot;) ? serviceUrl : &quot;http://&quot; + serviceUrl;
	}
	@Override
	public List<userauthenticationbean> findAll() {
		UserAuthenticationBean[] users = restTemplate.getForObject(serviceUrl+"/api/getUsers", UserAuthenticationBean[].class);
		return Arrays.asList(users);
	}
 
	@Override
	public UserAuthenticationBean findByUserNameAndPassword(String userName, String password) {
		UserAuthenticationBean user= new UserAuthenticationBean(); 
		user.setPassword(password);
		user.setUserName(userName);
		return restTemplate.postForObject(serviceUrl + &quot;/api/getUser&quot;,user,UserAuthenticationBean.class);
	}
 
	@Override
	public UserAuthenticationBean save(UserAuthenticationBean user) {
		return restTemplate.postForObject(serviceUrl + &quot;/api/addUser&quot;, user, UserAuthenticationBean.class);
	}
}
</userauthenticationbean>

After running this service on localhost:8081, you can fire HTTP request from client side and request to this service will be passed to producer microservice, in our scenario Authentication service. Also, you will be able to see instance of this microservice in Eureka server on localhost:9000 as below: tsblog4 To summarize, we understand about using microservices with Spring Boot. Also we learned some information on Eureka server and Netflix Ribbon for discovery service and Load balancing. You can learn more about microservices with spring from site: https://spring.io/blog/2015/07/14/microservices-with-spring

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

About Tatvasoft

TatvaSoft is a CMMi Level 3 and Microsoft Gold Certified Software Development Company offering custom software development services on diverse technology platforms, like Microsoft, SharePoint, Biztalk, Java, PHP, Open Source, BI, Big Data and Mobile.

Follow Us