Overview:

In my earlier post on Creating an Eureka Server using Spring Cloud, we have learned how to implement an spring cloud eureka server and in this post, I am going to register a Spring Boot Application as an eureka client into that eureka server.

From this article you will learn the basics of creating a Spring Boot Application and how to make it available in Eureka Server. At the end, you will also get the link to the full source code.

Prerequisite:

  • You need to have some hands-on experience in Maven, Java and Spring Boot.
  • You know what is @Autowired, @Entity, @Repository, @RestController and @PostConstruct.

The Eureka Client Spring Boot 2:

We have a tiny Spring Boot application named “Employee Manager”. It is a simple application which creates two employees after start up and writes into an in-memory HSQL Database. For writing into the database, we have used Spring JPA and There is a Rest API which can search an employee, if found it returns the Employee details with HTTP Status 200 OK, otherwise it returns HTTP Status 404 Not Found.

Project Structure – Spring Boot Initializer:

You can generate this maven project using Spring Initializr and Choose the dependencies JPA, Cloud Bootstrap, Eureka Discovery, Feign and Web.

The project structure is like –

src/main/
-- java/com/twodarray/employeemanager
        --- Employee.java
        --- EmployeeController.java
        --- EmployeeManager.java
        --- EmployeeManagerApplication.java
        --- EmployeeRepository.java
-- resources
        --- application.properties

Spring JPA Entity:

This Employee class is the JPA Entity of the application. In simple words, when you create an object of this class and save it through the JPA repository, it actually creates a row in the Employee table.

@Entity
public class Employee
{
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;
	private String name;
	private String title;

	public Long getId()
	{
		return id;
	}

	public void setId(Long id)
	{
		this.id = id;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public String getTitle()
	{
		return title;
	}

	public void setTitle(String title)
	{
		this.title = title;
	}

	@Override
	public String toString()
	{
		return "Employee{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", title='" + title + '\'' + '}';
	}
}

Spring JPA Repository:

The EmployeeRepository is the JPA Repository which helps to store the entities in the database. Not only storing, it handles all the database queries. The best part is, you don’t have to write a single implementation for the common queries (like INSERT, SELECT etc.), it is already handled by Spring JPA.

@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Long>
{
	Optional<Employee> findByName(String employeeName);
}

You can see, here I have just written an interface which extends CrudRepository from JPA library and just a method signature to find an employee by name. There is no implementation of this method in my project, but it actually solves our purpose. Only thing you just have to do is to follow some conventions advised by Spring.

You can find more information in the JPA Repositories Documentation provided by Spring.

Spring Rest Controller:

The EmployeeController is the class where I have written all the REST endpoints to communicate with this application. According to the below code, one can search an employee named “Alex” by using the URL like “http://localhost:8686/employees/John”. (Assuming the application is running on localhost at 8686 port.)

@RestController
public class EmployeeController
{
	@Autowired
	private EmployeeManager employeeManager;

	@GetMapping(
			value = "/employees/{name}",
			produces = {
					MediaType.APPLICATION_JSON_VALUE
			})
	public ResponseEntity<Employee> getEmployeeByName(
			@PathVariable(name = "name") String name
	)
	{
		Employee employee = employeeManager.getByName(name);
		if(employee == null)
		{
			return new ResponseEntity<>(HttpStatus.NOT_FOUND);
		}
		else
		{
			return new ResponseEntity<>(employee,HttpStatus.OK);
		}
	}
}

Employee Manager:

The EmployeeManager class is responsible of the implementation of the APIs exposed by the RestController. The below code will provide you an idea, how I have searched an employee by name from the database with the help of EmployeeRepository.

@Component
public class EmployeeManager
{
	@Autowired
	private EmployeeRepository employeeRepository;

	@PostConstruct
	public void init()
	{
		Employee employee1 = new Employee();
		employee1.setName("John");
		employee1.setTitle("Manager");
		employeeRepository.save(employee1);

		Employee employee2 = new Employee();
		employee2.setName("Alex");
		employee2.setTitle("Developer");
		employeeRepository.save(employee2);
	}

	public Employee getByName(String name)
	{
		Optional<Employee> employee = employeeRepository.findByName(name);
		if(employee.isPresent())
		{
			return employee.get();
		}
		else
		{
			System.out.println("Employee could not be found with name "+name);
			return null;
		}
	}
}

Note: I have used @PostConstruct annotation to create some dummy employees just after the application starts.

Well, our spring boot application is now ready. The next thing we will do is, we will register it in Eureka.

Note : If you don’t have any Eureka Server, you can check my earlier post Creating an Eureka Server using Spring Cloud or directly download it from GitHub

The Eureka Client Configuration:

To make the spring boot application as an eureka client, there are some simple steps. I am assuming that your eureka server is running at http://localhost:9091. So, the first thing you need to do is to put an annotation in the main class and then just need to add a configuration in the Employee Manager Application’s properties file.

Eureka Client Annotation:

The annotation we can use to register it in Eureka is @EnableDiscoveryClient ( You can also use @EnableEurekaClient annotation ). You have to put this annotation in the main class like below.

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

Note : @EnableDiscoveryClient is an annotation from the spring-commons library which can pick the “Discovery Service” implementations from the classpath and works for Eureka, Consul and Zookeeper, but @EnableEurekaService will only work for Eureka and it is from the spring-cloud-netflix library.

Eureka Client Properties:

Along with the annotation, you have to put a eureka specific configuration in the application.properties file of your application to make your application know where the eureka server is running. That’s it.

eureka.client.serviceUrl.defaultZone=http://localhost:9091/eureka/

Now, if you run the employee-manager application, it will register himself in the Eureka Server running at http://localhost:9091 like below.

Application Specific Configuration:

# Name of the application which will be registered in Eureka
spring.application.name=employee-manager 

# Port where you want to run this application
server.port=8686

# HSQLDB related configurations
spring.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver
spring.datasource.url=jdbc:hsqldb:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create

Note : If you want to run another instance of this application, you have to just change the “server.port” in the properties file and run it. The second instance will also be registered in Eureka.

Conclusion:

So in this post we have learned how to create a simple spring boot application and register it in Eureka Server.

Please find the full source code of this Employee Manager Application in the GitHub Page of 2DArray Blog.

If you have any questions, feel free to ask in the comment section.
Request you to Like, Share. 😀

LEAVE A REPLY

Please enter your comment!
Please enter your name here