반응형

[Spring Boot #22] 스프링 부트 DBCP 및 MySQL 연동해보기

반응형

| DBCP란


  • DBCP(Database Connection Pool)은 특정 DB에 커넥션 객체를 미리 만들어 놓고 그 커넥션이 필요할 때마다 어플리케이션에 할당하는 개념입니다. 마치 어떤 풀(저장소)에 아이템을 미리 담가놓고 필요할 때 꺼내는 것이라 생각하면 됩니다. 
  • 커넥션 객체를 만드는 것이 큰 비용을 소비하기 때문에 미리 만들어진 커넥션 정보를 재사용하기 위해 나온 테크닉입니다.
  • 스프링 부트에서는 기본적으로 HikariCP라는 DBCP를 기본적으로 제공합니다.

    (https://github.com/brettwooldridge/HikariCP#frequently-used)



| 스프링 부트 DBCP 설정


  • DBCP 설정은 애플리케이션 성능에 중요한 영향을 미치므로 신중히 고려해야하는 부분입니다.
  • 커넥션 풀의 커넥션 개수를 많이 늘린다고 해서 제대로된 성능이 나오는 것은 아닙니다. 왜냐하면 커넥션은 CPU 코어의 개수만큼 스레드로 동작하기 때문입니다.
  • 스프링에서 DBCP를 설정하는 방법은 다음과 같습니다. spring.datasource.hikari.maximum-pool-size=4 는 커넥션 객체의 최대 수를 4개로 설정하겠다는 의미입니다.
# application.properties
spring.datasource.hikari.maximum-pool-size=4


| 스프링 부트 MySQL 커넥터 설정


의존성 추가

<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.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>


| MySQL 도커 컨테이너 띄우기 - Linux 기준


  • 도커(docker)란 오픈소스 컨테이너 프로젝트입니다. 기존 가상머신과 다르게 게스트 OS를 사용하지 않고 기존 운영체제와 커널을 공유하기 때문에 빠르게 기존 운영환경과 격리된 환경인 컨테이너를 로딩되고 실행할 수 있습니다. 
  • 도커를 설치하는 방법은 다음 링크를 보시면 됩니다.
  • 도커를 설치한 뒤 다음 명령어를 입력합니다.

sudo docker run -p 3306:3306 --name mysql_boot -e MYSQL_ROOT_PASSWORD=1 -e MYSQL_DATABASE=springboot -e MYSQL_USER=saelobi
-e MYSQL_PASSWORD=pass -d mysql

각 옵션에 대한 설명은 다음과 같습니다.

  • -p 3306:3306은 도커의 3306 포트를 로컬 호스트의 3306 포트에 연결하라는 것을 나타냅니다.
  • --name mysql_boot는 도커 컨테이너의 이름을 지정합니다.
  • -e MYSQL_ROOT_PASSWORD=1 은 MySQL root 계정의 패스워드를 1로 설정한 것을 나타냅니다.
  • -e MYSQL_DATABASE=springboot는 MySQL에 springboot 데이터베이스를 만든 것을 뜻합니다.
  • -e MYSQL_USER=saelobi -e MYSQL_PASSWORD=pass 는 유저의 정보를 입력한 옵션입니다.
  • -d mysql 은 백그라운드에서 mysql 컨테이너를 띄우는 명령어 옵션입니다.

만일 mysql 이미지가 로컬에 없을 경우 mysql 이미지를 다운로드 받아 mysql 컨테이너를 로딩합니다.


sudo docker ps 

명령어를 치면 다음과 같이 mysql 컨테이너가 성공적으로 구동되고 있음을 알 수 있습니다.

sudo docker ps
[sudo] password for saelobi:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
5f702a61a948 mysql "docker-entrypoint.s…" 30 minutes ago Up 30 minutes 0.0.0.0:3306->3306/tcp, 33060/tcp mysql_boot


그 다음 application.properties 파일을 mysql 설정값에 맞추어 변경합니다.

# application.properties
spring.datasource.hikari.maximum-pool-size=4

spring.datasource.url=jdbc:mysql://localhost:3306/springboot
spring.datasource.username=saelobi
spring.datasource.password=pass


다음은 MySQL 데이터베이스에 접속하고 DML, DDL 문을 실행하기 위한 프로젝트 구조 및 소스 코드입니다.


프로젝트 구조

├── pom.xml
├── spring-boot-tutorial.iml
└── src
├── main
│   ├── java
│   │   └── com
│   │   └── tutorial
│   │   └── springboottutorial
│   │   ├── MySQLRunner.java
│   │   └── SpringBootTutorialApplication.java
│   └── resources
│   ├── application.properties
│   ├── static
│   └── templates


소스 코드

@SpringBootApplication
public class SpringBootTutorialApplication {

public static void main(String[] args) {
SpringApplication.run(SpringBootTutorialApplication.class, args);
}

}
@Component
public class MySQLRunner implements ApplicationRunner {

@Autowired
DataSource dataSource;

@Autowired
JdbcTemplate jdbcTemplate;

@Override
public void run(ApplicationArguments args) throws Exception {
try(Connection connection = dataSource.getConnection()){
System.out.println(connection);
String URL = connection.getMetaData().getURL();
System.out.println(URL);
String User = connection.getMetaData().getUserName();
System.out.println(User);

Statement statement = connection.createStatement();
String sql = "CREATE TABLE USER(" +
"ID INTEGER NOT NULL," +
"NAME VARCHAR(255)," +
"PRIMARY KEY(ID))";
statement.executeUpdate(sql);
}

jdbcTemplate.execute("INSERT INTO USER VALUES(1, 'saelobi')");
}
}


위 스프링 부트 어플리케이션을 실행한 후, 테이블 생성 및 데이터 적재 여부는 MySQL 컨테이너에 접속해서 확인을 할 수 있습니다.

sudo docker exec -i -t mysql_boot bash

위 명령어는 MySQL 컨테이너 상에서 bash를 실행하는 명령어입니다. 

  • exec : 컨테이너 외부에서 컨테이너 안의 명령을 실행하는 명령어입니다.
  • -i, --interactive=false : 표준 입력을 활성화하며 컨테이너와 연결되어 있지 않더라도 표준 입력을 유지합니다.
  • -t, --tty=false: TTY 모드를 사용합니다. Bash를 사용하려면 이 옵션을 설정해야 합니다. 이 옵션을 설정하지 않으면 명령을 입력할 수는 있지만 셸이 표시되지 않습니다.


컨테이너 bash를 실행한 후 mysql에 접속합니다.

mysql -u saelobi -p


mysql 접속 후 다음과 같이 Database의 목록을 확인할 수 있습니다.

mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| springboot |
+--------------------+
2 rows in set (0.01 sec)


springboot 데이터베이스에 접근하여 table 리스트와 적재된 데이터를 확인 할 수 있습니다.

mysql> use springboot;
Database changed
mysql> show tables;
+----------------------+
| Tables_in_springboot |
+----------------------+
| USER |
+----------------------+
1 row in set (0.01 sec)

mysql> select * from USER;
+----+---------+
| ID | NAME |
+----+---------+
| 1 | saelobi |
+----+---------+
1 row in set (0.00 sec)


참고자료 : https://www.inflearn.com/course/스프링부트


반응형

이 글을 공유하기

댓글

Designed by JB FACTORY