AWS Spring MariaDB 셋팅

간단설명

  1. Setting EC2(tomcatServer) and RDS(mariaDB) of aws.
    aws의 EC2와 RDS를 설정합니다.
  2. Check connection to use HeidiSQL success or not.
    HeidiSQL을 이용하여 커넥션 성공 여부를 확인합니다.
  3. Make war file use maven and upload it in EC2's Tomcat use FileZila.
    메이븐을 사용하여 war파일을 만들고 FileZila를 이용하여 EC2의 톰캣에 업로드 합니다.
  4. Check the result of configuration.
    결과를 확인 합니다.

개발환경(IDE, 언어, 프레임워크)

AWS EC2, AWS RDS
Intellij
java, Spring
MariaDB, Mybatis
thymeleaf

시스템 설정

1. EC2 설정(계정이 있다는 전제로 진행)

  1. login aws then click EC2.
    aws에 로그인 하여 EC2를 클릭합니다.

2.click the"인스턴스 시작" button.
인스턴스 시작 버튼을 누릅니다.

3.Choice Ubuntu Server 20.04.
우분투 서버 20.04를 선택합니다.

4.configure EC2. Do it to follow the pictures.
사진을 따라서 설정하시면 됩니다.

  1. Check the free teer useable.
    프리티어 사용가능을 선택해 줍니다.

  2. No need to change to configure at here.
    여기는 특별히 설정 할것이 없습니다.

  3. Set storage to 30GB.
    용량을 30GB로 늘려줍니다.

  4. Add tags (We don't add anything in this.)
    태그추가 (여기에는 아무것도 추가하지 않습니다.)

  5. Configure security group.(make it follow below picture.)
    보안그룹 설정 (아래 그림대로 만드세요.)

  6. Check your configuration then click start button.
    구성을 확인하고 시작버튼을 클릭합니다.

  7. Make keypair name and download
    키페어를 생성하고 다운로드 합니다.

  8. generate elastic ip.
    탄력적 ip를 생성해 줍니다.

  9. Click elatic ip address connect.
    탄력적 ip주소 연결을 클릭합니다.

  10. input your instance where marked by redbox.
    인스턴스를 빨간박스로 표시된 곳에 입력합니다.

  11. open the property of your pem file then move to security.
    we will remove users that haave checked underline.
    click the advanced button
    pem file의 속성에 가서 보안으로 갑니다.
    우리는 밑줄친 사용자를 제거할 것입니다.
    고급 버튼을 눌러주세요.

  12. click don't Inheritance.
    상속안함 클릭

  13. click edit.
    편집클릭

  14. delete names that checked underline.
    밑줄표시된 이름을 삭제 합니다.

  15. open the console with admin authority then move to folfer where have your pem file.
    관리자 권한으로 콘솔창을 열고 pem 파일이 있는 곳으로 이동합니다.

  16. check instance you make just before then click connect.
    방금전에 만든 인스턴스를 클릭하고 연결을 누르십시오

  17. type in consloe the keycode placed on pupple box.
    보라색 상자에 위치한 키값을 콘솔에 입력합니다.

  18. connect success.
    연결 성공.

2. RDB 설정

  1. Enter to aws's service then clidk RDS then click generate database.
    aws의 서비스에 들어거 RDS를 클릭하고 데이터베이스 생성을 클릭합니다.

  2. Configurate RDS follow the below picture.
    아래그림에 따라 RDS를 구성합니다.

  3. Enter to EC2's security grop then click generate security group
    EC2의 보안그룹에 들어간다음 보안그룹 생성을 클릭합니다.

  1. Input name and description then set inbound rule follow below picture.(this inbound rule is for dev so you should change to EC2's private ip when you deploy to Enterprise service.)
    이름과 설명을 작성하고 아래의 그림에 따라 인바운드 규칙을 만듭니다.
    (이 규칙은 개발용으로 상용으로 배포할때는 EC2의 private ip로 변경해야 합니다.)


  2. result screen shot
    결과 화면

heidiSQL로 접속하기

  1. Copy the endpoint and port marked by redbox.
    엔드포인트와 포트번호를 복사해 둡니다.

  2. Start heidiSQL then enter host, ip, user, password and port.( ip is RDS's endpoint)
    heidiSQL을 시작하고 ip, 사용자, 암호, 포트를 입력합니다.
    (ip는 RDS의 엔트포인트 입니다.)

3.result screen shot
결과화면

프로젝트 구조

spring Project construction

+---src
|   +---main
|   |   +---java
|   |   |   \---com
|   |   |       \---base
|   |   |           \---example
|   |   |                   BasicDao.java
|   |   |                   BasicDto.java
|   |   |                   HelloController.java
|   |   |                   BasicService.java
|   |   |                   
|   |   +---resources
|   |   |   |   logback.xml
|   |   |   |   mybatis-config.xml
|   |   |   |   
|   |   |   \---mappers
|   |   |           basic-Mapper.xml
|   |   |           
|   |   \---webapp
|   |       +---resources
|   |       |   +---css
|   |       |   \---js
|   |       \---WEB-INF
|   |           |   applicationContext.xml
|   |           |   dispatcher-servlet.xml
|   |           |   web.xml
|   |           |   
|   |           \---views
|   |                   hello.html
|   |  
|                 
|   pom.xml

디펜던시

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.base.example</groupId>
    <artifactId>base-set</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <jdk.version>11</jdk.version><!--기본설정-->
        <spring.version>5.2.3.RELEASE</spring.version><!--기본설정-->
        <thymeleaf.version>3.0.11.RELEASE</thymeleaf.version><!--기본설정-->
        <jcloverslf4j.version>1.7.31</jcloverslf4j.version><!--기본설정-->
        <logback.version>1.2.3</logback.version><!--기본설정-->
    </properties>

    <dependencies>
        <!--기본설정-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--기본설정-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--기본설정-->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>${thymeleaf.version}</version>
        </dependency>

        <!--기본설정-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>

        <!--기본설정-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${jcloverslf4j.version}</version>
        </dependency>

        <!--기본설정-->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
        </dependency>
        <!--디펜던시 기본설정-->

        <!--mariadb, mybatis 추가 설정-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client -->
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <version>2.7.4</version>
        </dependency>
        <!--mariadb, mybatis 추가 설정 end-->

    </dependencies>


    <build>
        <plugins>
            <!--플러그인 기본설정 시작-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
            <!--플러그인 기본설정 끝-->
        </plugins>
    </build>
</project>

web.xml 설정

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--기본설정 시작-->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--dispatcher 에 들어갈 지역변수-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/applicationContext.xml</param-value>>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--기본설정 종료-->


</web-app>

applicationContext 설정

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
">

    <!--기본설정 시작-->
    <import resource="dispatcher-servlet.xml"/>

    <context:component-scan base-package="com.base.*"/>
    <!--기본설정 끝-->

    <!--mariadb, mybatis 추가 설정-->
    <!-- MariaDB JDBC DataSource -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.mariadb.jdbc.Driver"/>
        <property name="url"
                  value="jdbc:mariadb://${DBendpoint}/${DBname}"/>
        <property name="username" value="${DBname}" />
        <property name="password" value="${DBPassword}" />
    </bean>

    <!-- mybatis SqlSessionFactoryBean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:/mybatis-config.xml" />
        <property name="mapperLocations" value="classpath:/mappers/**/*Mapper.xml" />
    </bean>

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="sqlSessionFactory"/>
    </bean>
  
  
</beans>

dispatcher-servlet 설정

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--spring - thymeleaf 기본설정 시작 -->
    <mvc:annotation-driven/>

    <mvc:resources mapping="/resources/**" location="/resources/"/>

    <bean id="templateResolver"
          class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".html" />
        <!--뷰리졸버에서 utf-8로 반환할것을 설정-->
        <property name="characterEncoding" value="utf-8" />
        <property name="templateMode" value="HTML5" />
    </bean>

    <!--바로위의 id="templateResolver" 설정을 가져와서 타임리프에 적용-->
    <bean id="templateEngine"
          class="org.thymeleaf.spring5.SpringTemplateEngine">
        <property name="templateResolver" ref="templateResolver" />
    </bean>

    <!--templateEngine bean을 매개로 타임리프 엔진에 templateResolver 의 설정을 전달-->
    <bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="templateEngine" />
        <!--뷰 리졸버에서 온 자료를 utf-8 형식으로 출력하게 설정-->
        <property name="characterEncoding" value="utf-8"/>
    </bean>
    <!--spring - thymeleaf 기본설정 끝-->
    
</beans>

controller 설정

package com.base.example;

import org.apache.commons.logging.Log;//기본임포트
import org.apache.commons.logging.LogFactory;//기본임포트
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;//기본임포트
import org.springframework.ui.Model;//기본임포트
import org.springframework.web.bind.annotation.GetMapping;//기본임포트


@Controller
public class HelloController {
    private static final Log LOG = LogFactory.getLog(HelloController.class );
    @Autowired
    BasicService testService;
    BasicDto basicDto;

    @GetMapping({"/"})
    public String hello(Model model) {
        LOG.info("hello 가동");
        basicDto = testService.get_id(basicDto);
        model.addAttribute("id", basicDto.getId());
        return "hello";
    }
    /*여기까지 기본설정*/
}

service 설정(Optional)

package com.base.example;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BasicService {
    private static final Log LOG = LogFactory.getLog(HelloController.class );

    @Autowired
    private BasicDao testDao;

    public BasicDto get_id(BasicDto basicDto){
        basicDto = testDao.get_id(basicDto);
        return basicDto;
    }
	//여기까지 기본 설정
}

DAO 설정 (Optional)

package com.base.example;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class BasicDao {
    private static final Log LOG = LogFactory.getLog(HelloController.class );
    @Autowired
    private SqlSession sqlSession;

    private final String NAMESPACE = "com.base.example.testMapper.";
    public BasicDto get_id(BasicDto basicDto){
        LOG.info("get_list 에 접근함.");
        basicDto = sqlSession.selectOne(NAMESPACE+"get_id");
        LOG.info("DB연결확인 : " + basicDto.toString());
        return basicDto;
    }
}

DTO 설정 (Optional)

package com.base.example;

import org.springframework.stereotype.Component;

@Component
public class BasicDto {
    private String id;

    public String getId() {
        return id;
    }

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

Mybatis 및 JPA 설정(Optinal)

테스트용 테이블 설정

enter below queries at you heidiSQL.
heidiSQL 에서 아래와 같은 쿼리를 입력해 주세요.

INSERT INTO `test`.`id` (`id`) VALUES ('id1');
SELECT `id` FROM `test`.`id` WHERE  `id`='id1' LIMIT 1;
INSERT INTO `test`.`id` (`id`) VALUES ('id2');
SELECT `id` FROM `test`.`id` WHERE  `id`='id2' LIMIT 1;
INSERT INTO `test`.`id` (`id`) VALUES ('id3');
SELECT `id` FROM `test`.`id` WHERE  `id`='id3' LIMIT 1;

mybatis-config.xml 설정

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <typeAliases>
        <typeAlias type="com.base.example.BasicDto" alias="BasicDto"/>
    </typeAliases>

</configuration>

basic-Mapper 설정

<select id="get_id" resultType="BasicDto">
    select id from id where id.id = "id2"
</select>

Javascript 설정

  • none

Html 설정

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" lang="ko">
<head>
    <meta charset="utf-8"/>
    <title th:text="'Hello ' + ${id} + '!'"></title>
    <link th:href="@{/resources/css/main.css}" rel="stylesheet"/>
</head>
<body>
<h2 class="hello-title" th:text="'Hello ' + ${id} + '!'"></h2>
<h3>쿨럭</h3>
<script th:src="@{/resources/js/main.js}"></script>
</body>
</html>

EC2에 war파일 배포

  1. select maven tap in inteliJ then click where marked redbox.
    intelij의 메이븐 탭을 선택하고 빨간박스로 표시된 곳을 클릭합니다.

  2. Double-click clean.
    clean을 더블클릭합니다.

[INFO] Scanning for projects...
[WARNING] 
[WARNING] Some problems were encountered while building the effective model for com.base.example:base-set:war:1.0-SNAPSHOT
[WARNING] 'dependencies.dependency.version' for org.projectlombok:lombok:jar is either LATEST or RELEASE (both of them are being deprecated) @ line 46, column 22
[WARNING] 
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING] 
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING] 
[INFO] 
[INFO] ---------------------< com.base.example:base-set >----------------------
[INFO] Building base-set 1.0-SNAPSHOT
[INFO] --------------------------------[ war ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-cli) @ base-set ---
[INFO] Deleting D:\aws\first\base-set\target
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.500 s
[INFO] Finished at: 2021-08-31T16:59:42+09:00
[INFO] ------------------------------------------------------------------------
  1. Double-clikc package.
    package를 두번 클릭합니다.
[INFO] Scanning for projects...
[WARNING] 
[WARNING] Some problems were encountered while building the effective model for com.base.example:base-set:war:1.0-SNAPSHOT
[WARNING] 'dependencies.dependency.version' for org.projectlombok:lombok:jar is either LATEST or RELEASE (both of them are being deprecated) @ line 46, column 22
[WARNING] 
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING] 
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING] 
[INFO] 
[INFO] ---------------------< com.base.example:base-set >----------------------
[INFO] Building base-set 1.0-SNAPSHOT
[INFO] --------------------------------[ war ]---------------------------------
Downloading from central: https://repo.maven.apache.org/maven2/org/projectlombok/lombok/maven-metadata.xml
Downloaded from central: https://repo.maven.apache.org/maven2/org/projectlombok/lombok/maven-metadata.xml (1.8 kB at 1.7 kB/s)
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ base-set ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 3 resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.3:compile (default-compile) @ base-set ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 4 source files to D:\aws\first\base-set\target\classes
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ base-set ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\aws\first\base-set\src\test\resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.3:testCompile (default-testCompile) @ base-set ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ base-set ---
[INFO] No tests to run.
[INFO] 
[INFO] --- maven-war-plugin:2.2:war (default-war) @ base-set ---
[INFO] Packaging webapp
[INFO] Assembling webapp [base-set] in [D:\aws\first\base-set\target\base-set-1.0-SNAPSHOT]
[INFO] Processing war project
[INFO] Copying webapp resources [D:\aws\first\base-set\src\main\webapp]
[INFO] Webapp assembled in [213 msecs]
[INFO] Building war: D:\aws\first\base-set\target\base-set-1.0-SNAPSHOT.war
[INFO] WEB-INF\web.xml already added, skipping
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  6.763 s
[INFO] Finished at: 2021-08-31T17:07:39+09:00
[INFO] ------------------------------------------------------------------------

Process finished with exit code 0
  1. war-file is generated.
    war파일이 생성되었습니다.

  2. move the war-file then change the name what you want.
    war파일을 적절한 곳에 옮기고 원하는 이름으로 바꿔주세요.

  3. open FileZilla then click the mark of redbaox.
    파일질라를 열어준다음 빨간박스 표시를 클릭하세요.

  4. Enter EC2's elastic ip to host, port of ssh type of EC2's security-group to port, user-name of EC2 to name, local computer's key-file location to kefile.
    호스트에 EC2의 탄력적 IP주소,포트에 EC2보안그룹의 ssh타입의 포트를 적어주고 사용자에 EC2의 사용자명, 키파일에 로컬 컴퓨터의 pem파일경로를 지정해 줍니다.

  5. you can see the screen as below then.
    그러면 아래와 같은 화면을 볼 수 있습니다.

  6. Double click '/' in remote site then goto /var/lib/tomcat9/webapps then upload you war-file.
    리모트 사이트의 '/'를 더블 클릭하고 /var/lib/tomcat9/webapps 경로로 이동하고 war-file을 업로드 합니다.

결과

  1. open borwser then enter your EC2's elastic-ip:port(useally 8080)/your war file name then you can see the screen as below.
    브라우저를 열고 EC2의 탄력적ip주소/톰캣의 포트/war파일 이름을 입력합니다.
    그러면 다음과 같은 화면을 볼수 있습니다.

좋은 웹페이지 즐겨찾기