Create microservices with Spring Boot

Introduction

Some of the projects I was involved in previously adopted an architecture called microservices. It seems that the word "micro service" has been very popular for a long time, but at that time I didn't know about it, and I remember being embarrassed when I misunderstood that it was a Microsoft service. However, even at that time, I finished development with a vague understanding due to the busyness of the project, so I felt a sense of crisis if I completely forgot everything as it was, and decided to study hard. I made one service with Java and Spring Boot before, but this time I would like to create a microservice in a similar environment as a review. It's a very simple REST service to create.

What is microservices?

The explanation I actually received was that, unlike conventional applications (which are said to be monolithic applications), where one application has all the functions, we have developed multiple small (micro) services individually. It was like working together to create one big system. In short, microservices are, in a broad sense, a software creation method. Services created based on this idea were also called microservices.

At that time, I was convinced that it was understandable, but the more I looked it up, the more the explanations differed slightly from person to person, and I was confused about the definition of microservices. That should be it, microservices are so-called buzzwords, and it seems that there is no strict definition. Among them, the features that are often mentioned are as follows.

-Each service can be deployed independently -Each service operates in a process and communicates with a lightweight API (HTTP, etc.) ・ Services are divided from a business perspective ・ Each service is automatically deployed ・ Eliminate centralized management as much as possible. Do not control language, DB, development team (in short, each service can be written in a different program language etc.)

merit

I won't go into too much here, but if you look at the benefits of developing microservices, you'll see a lot. When I actually decided to create one service, most of the other services were developed in the go language. Of course, I was also told to develop in the same language unless there was a special reason, but at that time I had never touched it, "I can not implement it while studying from now on even though the delivery date is near. As a result of kneading "Desu" with all my might, I was told with a bitter smile, permission to develop in Java that I was accustomed to writing, and how to create an environment. This kind of selfishness passed

Eliminate centralized management as much as possible. Do not control language, DB, development team

I think this is one of the advantages of microservices. Also, since each one is a loosely coupled service, I would like to try some new technology, but I'm a little scared. Even in such cases, you can choose a service with low risk and try it.

Demerit

Of course, there are various disadvantages. By splitting the services, each service is simple, but overall it becomes very complicated. Also, ・ You may write in different languages for each service. ・ Easy to try new technology Regarding the points mentioned as merits such as, it is good when developing a new one, but when it comes to maintenance, it seems to be a disadvantage because it is necessary to gather engineers who can handle each.

What is Spring Boot?

It is a framework for easily building web applications with the Spring Framework, which is a Java framework. Since the executable file contains a web container (tomcat or jetty), it can be launched as one application without preparing a separate web server.

Prepare development environment

Install Java and Maven to create in Java. (I have confirmed the operation with JDK1.8.) The PC I used was a Mac, so ↓ was helpful. https://qiita.com/amemolee/items/6f33b8e321cc9395b0cf

Install Spring Tool Suite (STS). STS is an integrated development environment specializing in Spring Framework development. The base is Eclipse. The basic operation method is almost Eclipse. Download and install from ↓. https://spring.io/tools

I want to run the created application with docker, so I will put docker in it. https://docs.docker.com/docker-for-mac/install/

By the way, my environment is as follows. -JDK 1.8 ・ Maven 3.6.0 ・ Spring Tool Suite 4.0.1

Creating a service

Then I will make it immediately.

Creating a project

  1. After opening the STS, select File> New> Spring Starter Project.
  2. Decide on a project name and package, and click "Next". スクリーンショット 2018-12-16 18.57.53.png
  3. Since it will move to the setting of Dependencies, check [Web] → [Web] and click "Finish". スクリーンショット 2018-12-16 18.52.33.png I think you can create a project with the name you set in the second step. In addition, the automatically generated Java source code is included in the configured package. If you created as shown in the image above, the "testservice" project should be created and "TestserviceApplication.java" should be created in the com.microservice package under src / main / java. スクリーンショット 2018-12-17 1.30.33.png

Edit source

Edit the generated Java source file.

TestserviceApplication.java


package com.microservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class TestserviceApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestserviceApplication.class, args);
    }
}
@RestController
class HomeController {
    @RequestMapping("/")
    public HogeTest getSentence() {
        return new HogeTest("test");
    }
}
class HogeTest {
    private String info;
    public HogeTest (String info) {
        this.setInfo(info);
    }
    public String getInfo() {
        return info;
    }
    public void setInfo(String info) {
        this.info = info;
    }
}

It is a process that returns a simple JSON. The contents of the source code will be omitted this time. When you edit the source, you can check it by executing [Run] → [Run As] → [Spring Boot App] in the STS field, but for the time being, let's move on to the explanation of creating an executable file.

Creating an executable file

Create a jar file with Maven's install function. In the terminal, go to the project directory "testservice" and execute the following command.

mvn install

If successful, you should have an executable file named "testservice-0.0.1-SNAPSHOT.jar" under your target directory. Let's do this. Execute the following command from directly under the project directory "testservice".

java -jar target/testservice-0.0.1-SNAPSHOT.jar

Access "http : // localhost: 8080" with a browser, and if the following is displayed, it is OK.

スクリーンショット 2018-12-18 2.10.16.png

After confirming, stop the service by pressing "control + c" in the terminal.

Deploy to Docker

Finally, deploy the executable as a Docker image. Docker is a container-based virtualization service. A container is a somewhat independent process execution environment that is isolated from other processes. The program created this time can also be run on the Docker container. Similar to the JVM, Docker absorbs differences in OS. Therefore, if the program can be run on the container, it can be easily moved to other environments such as the production environment. (It is assumed that Docker is also included in that environment.)

Creating a Docker image

Now, let's create a Docker image, which is the file system required to create a Docker container. Prepare the executable file "testservice-0.0.1-SNAPSHOT.jar" created this time, and create a text file named "Dockerfile" in the same directory. A Dockerfile is a file that contains instructions for building an image. In the file, describe as follows.

Dockerfile


FROM frolvlad/alpine-oraclejdk8:slim
ADD testservice-0.0.1-SNAPSHOT.jar app.jar
RUN sh -c 'touch /app.jar'
ENV JAVA_OPTS=""
ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:dev/./urandom -jar /app.jar"]

Once you have a Dockerfile, you can build the image with the following command.

docker build -t microtest ./

Start container

Start the container based on the created image with the following command.

docker run -p 8080:8080 -d -t microtest

It is difficult to understand because it is running in the background, but you can check whether it is running with the following command.

docker ps

It is OK if it is displayed like ↓. スクリーンショット 2018-12-18 2.06.10.png

If you try to access "http : // localhost: 8080" again with a browser, you will see {"info": "test"} in JSON format as before.

at the end

I tried to create it for the time being, but there are still some parts that do not meet the above features such as deployment automation. SpringBoot has a function that is automatically executed at build time if you write test code in JUnit etc. and place it in the specified place. You can also deploy to Docker. In other words, it is possible to run the test when building, create an executable file if it passes, and deploy it to Docker, but ~~ I forgot how to do it ~~ It will be long, so I will take another opportunity. ..

Reference site

https://blog.guildworks.jp/2015/01/27/docker-with-spring-boot/

Recommended Posts

Create microservices with Spring Boot
Create an app with Spring Boot 2
Create an app with Spring Boot
Download with Spring Boot
Create a simple search app with Spring Boot
Create CRUD apps with Spring Boot 2 + Thymeleaf + MyBatis
Create your own Utility with Thymeleaf with Spring Boot
Create Spring Boot environment with Windows + VS Code
Create a web api server with spring boot
Create a Spring Boot development environment with docker
Create Spring Cloud Config Server with security with Spring Boot 2.0
Generate barcode with Spring Boot
Implement GraphQL with Spring Boot
Get started with Spring boot
Hello World with Spring Boot!
Run LIFF with Spring Boot
SNS login with Spring Boot
File upload with Spring Boot
Spring Boot starting with copy
Spring Boot starting with Docker
Set cookies with Spring Boot
Use Spring JDBC with Spring Boot
Add module with Spring Boot
Getting Started with Spring Boot
Send email with spring boot
Create Restapi with Spring Boot ((1) Until Run of App)
Create a simple demo site with Spring Security with Spring Boot 2.1
Use Basic Authentication with Spring Boot
gRPC on Spring Boot with grpc-spring-boot-starter
Hot deploy with Spring Boot development
Database linkage with doma2 (Spring boot)
Spring Boot programming with VS Code
Until "Hello World" with Spring Boot
Inquiry application creation with Spring Boot
Get validation results with Spring Boot
(Intellij) Hello World with Spring Boot
Google Cloud Platform with Spring Boot 2.0.0
Check date correlation with Spring Boot
I tried GraphQL with Spring Boot
[Java] LINE integration with Spring Boot
Beginning with Spring Boot 0. Use Spring CLI
I tried Flyway with Spring Boot
Message cooperation started with Spring Boot
Spring Boot gradle build with Docker
Processing at application startup with Spring Boot
Create Spring Boot development environment on Vagrant
Hello World with Eclipse + Spring Boot + Maven
Send regular notifications with LineNotify + Spring Boot
Perform transaction confirmation test with Spring Boot
How to create your own Controller corresponding to / error with Spring Boot
HTTPS with Spring Boot and Let's Encrypt
Create Spring Boot-gradle-mysql development environment with Docker
Challenge Spring Boot
Try using Spring Boot with VS Code
Create Java Spring Boot project in IntelliJ
Start web application development with Spring Boot
Launch Nginx + Spring Boot application with docker-compose
I tried Lazy Initialization with Spring Boot 2.2.0
Spring Boot Form
Implement CRUD with Spring Boot + Thymeleaf + MySQL
Asynchronous processing with Spring Boot using @Async