Let's make a simple API with EC2 + RDS + Spring boot ①

Overview

This is the procedure to deploy the spring boot project on the EC2 instance and create a very simple API. In ①, first deploy the project on EC2 and create an API that returns POJO.

Goal of this article

First, build a very simple REST API that returns POJOs on your EC2 instance. It will be the next time to connect to MySQL and get the data.

Target person

This article does not explain spring boot or AWS in detail. Therefore, for those who want to try AWS using spring for the time being.

This article is based on the following environment and knowledge.

environment

1. Create spring boot project ~ REST API construction

Project creation

First, generate a template for the spring boot project with Spring initializr. As the name suggests, spring initializr makes it easy to create a template for a spring boot project. In addition to being able to specify the version, it is very convenient because you can create a template with the specified library etc. included.

Let's leave Group and Artifact as they are. The important thing is Dependencies. Let's add the following to Dependencies.

When added, it will be as follows. screenshot-start.spring.io-2019.01.31-20-35-37.png

Press Generate Priject to download the project.

API construction

Unzip the project you downloaded earlier and open it in an IDE. This article uses intelliJ.

First, comment out the JPA and MySQL libraries in pom.xml. I will not use it in this article, but I will use it from the next time. Also, if you do not comment out here, it will cause an error later.

pom.xml


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

		<!--<dependency>-->
			<!--<groupId>mysql</groupId>-->
			<!--<artifactId>mysql-connector-java</artifactId>-->
			<!--<scope>runtime</scope>-->
		<!--</dependency>-->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
...

** Let's make the package structure under main as follows **

main └ java   ┗ com.example.demo     ┣ controller        └ PersonController.java     ┣ service        └ PersonService.java     ┣ model        └ Person.java     └ DemoApplication.java

It's okay if it looks like the following in intelliJ. スクリーンショット 2019-02-05 0.21.55.png

** Then rewrite each file as follows **

Person.java


@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Data
public class Person {
    private String name;
    private Integer age;
    private String gender;
}

PersonService.java


@Service
public class PersonService {
    public Person getPerson(){
        return new Person().builder()
            .name("hoge")
            .age(16)
            .gender("man")
            .build();
    }
}

PersonController.java


@RestController
@RequiredArgsConstructor
public class PersonController {
    private final PersonService personService;

    @RequestMapping(path= "person", method = RequestMethod.GET)
    public Person getPerson(){
        return personService.getPerson();
    }
}

** Let's do it **

If you access http: // localhost: 8080 / person and get the following response, it's okay. スクリーンショット 2019-02-05 0.30.33.png

Package

Package the project created this time for execution on the EC2 instance.

$ mvn clean package

This will generate a jar file in target /.

2. Create an EC2 instance ~ Try accessing the instance from the terminal

Now let's create an EC2 instance.

Create an EC2 instance

First, let's access AWS.

** ① Move to EC2 from the service on the toolbar. ** ** screenshot-us-east-2.console.aws.amazon.com-2019.02.05-11-02-17.png

** ② Click Create Instance. ** ** screenshot-us-east-2.console.aws.amazon.com-2019.02.05-11-02-50.png

** ③ Select Amazon Linux at the top. ** ** screenshot-us-east-2.console.aws.amazon.com-2019.02.05-11-03-07.png

** ④ Go to instance details settings ** screenshot-us-east-2.console.aws.amazon.com-2019.02.05-11-03-32.png

** ⑤ Skip to the security group settings page ** screenshot-us-east-2.console.aws.amazon.com-2019.02.05-11-06-15.png

** ⑥ Add rules ** screenshot-us-east-2.console.aws.amazon.com-2019.02.05-11-06-54.png Click Confirm and Create when you are done.

** ⑦ Launch instance ** Click Start to start the instance. screenshot-us-east-2.console.aws.amazon.com-2019.02.05-11-07-35.png

** ⑧ Creating a key pair ** First, enter the key pair name. After downloading, create an instance. screenshot-us-east-2.console.aws.amazon.com-2019.02.05-11-08-17.png

This completes the instance creation.

Try ssh access to your EC2 instance

Let's take a look at the instance information created earlier. ** Make a copy of the public DNS. ** ** screenshot-us-east-2.console.aws.amazon.com-2019.02.05-11-12-13.png

Let's ssh access the EC2 instance using the downloaded pem file.

$ ssh -i ~/Downloads/demo.pem ec2-user@The public DNS you copied earlier

//Let's yum update just in case
$ sudo yum update

** * Originally, place the pem file in an appropriate location such as under .ssh /. ** **

If you can access it, let's execute a nice command. (Ls, cd, etc.)

Place the jar file on your EC2 instance

Use the sftp command to place the jar file under target created locally on the ec2 instance.

Log out from the instance with ʻexit` etc. or move to the directory of the spring boot project earlier in another tab.

Now transfer the file with sftp.

$ sftp -i ~/Downloads/demo.pem ec2-user@The public DNS you copied earlier

$ sftp> put target/demo-0.0.1-SNAPSHOT.jar
Uploading target/demo-0.0.1-SNAPSHOT.jar to /home/ec2-user/demo-0.0.1-SNAPSHOT.jar
targ 100%   18MB   1.1MB/s   00:16

After the upload is complete, try logging in to your EC2 instance again.

$ ssh -i ~/Downloads/demo.pem ec2-user@The public DNS you copied earlier

 __|  __|_  )
       _|  (     /   Amazon Linux AMI
      ___|\___|___|

$ ls
demo-0.0.1-SNAPSHOT.jar

Make sure the jar file is uploaded with the ls command.

jar file execution

Now run the jar on the ec2 instance.

$ $ java -jar demo-0.0.1-SNAPSHOT.jar
Exception in thread "main" java.lang.UnsupportedClassVersionError: org/springframework/boot/loader/JarLauncher : Unsupported major.minor version 52.0
	at java.lang.ClassLoader.defineClass1(Native Method)
	at java.lang.ClassLoader.defineClass(ClassLoader.java:808)
	at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
	at java.net.URLClassLoader.defineClass(URLClassLoader.java:443)
	at java.net.URLClassLoader.access$100(URLClassLoader.java:65)
	at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
	at java.net.URLClassLoader$1.run(URLClassLoader.java:349)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:348)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:430)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:323)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
	at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482)

Oops, an error has occurred. I developed with Java 1.8 locally this time, but an error occurs because the Java version included by default in Amazon linux is 1.7.

$ java -version
java version "1.7.0_201"
OpenJDK Runtime Environment (amzn-2.6.16.0.78.amzn1-x86_64 u201-b00)
OpenJDK 64-Bit Server VM (build 24.201-b00, mixed mode)

First, let's install Java 1.8.

$ sudo yum install -y java-1.8.0-openjdk.x86_64

Switch versions with the ʻalternatives` command

$ sudo alternatives --config java

There are 2 programs'java'To provide.

Select command
-----------------------------------------------
*+ 1           /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java
   2           /usr/lib/jvm/jre-1.8.0-openjdk.x86_64/bin/java

Press Enter to select the current[+]Or enter the selection number:2

$ java -version
openjdk version "1.8.0_191"
OpenJDK Runtime Environment (build 1.8.0_191-b12)
OpenJDK 64-Bit Server VM (build 25.191-b12, mixed mode)

After confirming that the version has been switched, try again.

$ java -jar demo-0.0.1-SNAPSHOT.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.2.RELEASE)
~
2019-02-05 02:55:55.282  INFO 8556 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
~

If you can start it safely, try accessing it from a browser or with curl.

スクリーンショット 2019-02-05 12.13.48.png
$ curl http://DNS of the created ec2 instance:8080/person
{"name":"hoge","age":16,"gender":"man"}

Json is returned safely.

That's all for creating an API easily with EC2 + spring boot. There are many places where I broke, so it would be helpful if you could comment on the points you stumbled upon.

next time Try to make a simple API with EC2 + RDS + Spring boot ② * Writing

Recommended Posts

Let's make a simple API with EC2 + RDS + Spring boot ①
Implement a simple Rest API with Spring Security with Spring Boot 2.0
Implement a simple Rest API with Spring Security & JWT with Spring Boot 2.0
Implement a simple Web REST API server with Spring Boot + MySQL
Let's make a book management web application with Spring Boot part1
Let's make a book management web application with Spring Boot part3
Let's make a book management web application with Spring Boot part2
I made a simple search form with Spring Boot + GitHub Search API.
Create a simple search app with Spring Boot
Create a web api server with spring boot
Create a simple demo site with Spring Security with Spring Boot 2.1
[Beginner] Let's write REST API of Todo application with Spring Boot
Let's make a Christmas card with Processing!
Create a simple on-demand batch with Spring Batch
HTTPS with Spring Boot and Let's Encrypt
Let's make a smart home with Ruby!
[docker] [nginx] Make a simple ALB with nginx
[Rails] Let's create a super simple Rails API
Java beginner tried to make a simple web application using Spring Boot
Create a website with Spring Boot + Gradle (jdk1.8.x)
Let's make a search function with Rails (ransack)
Create a Spring Boot development environment with docker
I tried to make a simple game with Javafx ① "Let's find happiness game" (unfinished)
Download with Spring Boot
Automatically map DTOs to entities with Spring Boot API
Hello World (REST API) with Apache Camel + Spring Boot 2
Let's make a LINE Bot with Ruby + Sinatra --Part 2
[Spring Boot] Get user information with Rest API (beginner)
[JUnit 5 compatible] Write a test using JUnit 5 with Spring boot 2.2, 2.3
[Java basics] Let's make a triangle with a for statement
Let's make a robot! "A simple demo of Java AWT Robot"
Customize REST API error response with Spring Boot (Part 2)
[JUnit 5] Write a validation test with Spring Boot! [Parameterization test]
A memorandum when creating a REST service with Spring Boot
Let's make a LINE Bot with Ruby + Sinatra --Part 1
Customize REST API error response with Spring Boot (Part 1)
I wrote a test with Spring Boot + JUnit 5 now
I tried to make a simple game with Javafx ① "Let's find happiness game" (unfinished version ②)
Let's write a proxy integrated Lambda function of Amazon API Gateway with Spring Cloud Function
Let's make a circuit breaker for back-end service using Actuator of Spring Boot (Part 1)
A story that stumbled when deploying a web application created with Spring Boot to EC2
Let's write how to make API with SpringBoot + Docker from 0
Generate barcode with Spring Boot
Hello World with Spring Boot
Implement GraphQL with Spring Boot
Handle Java 8 date and time API with Thymeleaf with Spring Boot
Implement REST API with Spring Boot and JPA (Application Layer)
Implement REST API with Spring Boot and JPA (Infrastructure layer)
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
Try hitting the zip code search API with Spring Boot
Spring Boot starting with Docker
Hello World with Spring Boot
Set cookies with Spring Boot
Use Spring JDBC with Spring Boot
Add module with Spring Boot
Getting Started with Spring Boot
Link API with Spring + Vue.js