일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
- Spring Boot
- AJAX
- 설정
- JavaScript
- spring
- 문서
- Eclipse
- Thymeleaf
- jpa
- 오픈소스
- Docker
- Core Java
- MSSQL
- Source
- myBatis
- ubuntu
- MySQL
- STS
- oracle
- Tomcat
- IntelliJ
- Open Source
- PostgreSQL
- Exception
- Python
- maven
- error
- git
- SpringBoot
- JDBC
- Today
- Total
헤르메스 LIFE
[SpringBoot] MySQL/Maria 연결하기 본문
IDE : IntelliJ
JDK : OpenJDK 11
Framework : Spring Boot 2.5.2
Database : MySql 최신버전 ( Oracle 에 라이센스비를 지급해야 하고, 소스공개의 의무가 존재함 )
Maria 최신버전 ( 소스공개의 의무가 존재함 )
Docker 설치
https://hermeslog.tistory.com/497?category=302346
Docker에 MySQL 설치
? docker에 mysql 이미지 설치
$>docker pull mysql
? Docker 컨테이너 생성
? -d : 백그라운드 실행
? -p 포트 포딩 3306 번 포트로 들어온 내용은 3306 번 포트로 포딩을 해주겟다는 내용
? -e 환경변수 설정 MYSQL_ROOT_PASSWORD= 내용을 password로 설정
? --name Container 이름을 설정해줍니다.
? --restart=always Docker 실행 시 같이 실행됨.
? docker exec -> run a command on an existing/running container
? docker run -> create a new container from an image, and run the command there
? local에 데이터 저장 : -v c:\Temp\data\mariadb:/var/lib/mysql
$>docker run -d -p 3306:3306 --name mysql_boot -e MYSQL_ROOT_PASSWORD=1 -e MYSQL_DATABASE=springboot -e MYSQL_USER=hermeswing -e MYSQL_PASSWORD=pass -v c:\Temp\data\mysql:/var/lib/mysql -d mysql
? 생성된 Docker 컨테이너 확인
$>docker ps -a
? Docker 컨테이너 실행
$>docker exec -it mysql_boot bash
? MySQL 접속 password : 1
$>mysql -u root -p
? MySQL version 확인
mysql> select version();
? Docker 컨테이너 멈춤
$>docker stop mysql_boot
? Docker 컨테이너 삭제
$>docker rm mysql_boot
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.mysql</groupId>
<artifactId>MySqlRunner</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>MySqlRunner</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.mysql.mysqlrunner.runner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Statement;
@Component
public class MySQLRunner implements ApplicationRunner {
@Autowired
DataSource dataSource;
@Autowired
JdbcTemplate jdbcTemplate;
@Override
public void run( ApplicationArguments args ) {
try {
Connection connection = dataSource.getConnection();
System.out.println( connection.getMetaData().getClass() );
System.out.println( connection.getMetaData().getURL() );
System.out.println( connection.getMetaData().getUserName() );
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, 'hermeswing')" );
} catch( Exception e ) {
e.printStackTrace();
}
}
}
server.port=9090
spring.datasource.hikari.maximum-pool-size=4
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?allowPublicKeyRetrieval=true
spring.datasource.username=hermeswing
spring.datasource.password=pass
MySQLRunner 실행결과
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.5.2)
2021-07-18 13:38:50.394 INFO 11432 --- [ main] c.m.mysqlrunner.MySqlRunnerApplication : Starting MySqlRunnerApplication using Java 11 on DESKTOP-HMJ6ST0 with PID 11432 (C:\JetBrains\IdeaProjects\MySqlRunner\target\classes started by hermeswing in C:\JetBrains\IdeaProjects\MySqlRunner)
2021-07-18 13:38:50.404 INFO 11432 --- [ main] c.m.mysqlrunner.MySqlRunnerApplication : No active profile set, falling back to default profiles: default
2021-07-18 13:38:51.840 INFO 11432 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 9090 (http)
2021-07-18 13:38:51.851 INFO 11432 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-07-18 13:38:51.851 INFO 11432 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.48]
2021-07-18 13:38:51.951 INFO 11432 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-07-18 13:38:51.951 INFO 11432 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1447 ms
2021-07-18 13:38:52.385 INFO 11432 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 9090 (http) with context path ''
2021-07-18 13:38:52.397 INFO 11432 --- [ main] c.m.mysqlrunner.MySqlRunnerApplication : Started MySqlRunnerApplication in 2.765 seconds (JVM running for 5.276)
2021-07-18 13:38:52.400 INFO 11432 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-07-18 13:38:52.681 INFO 11432 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
class com.zaxxer.hikari.pool.HikariProxyDatabaseMetaData
jdbc:mysql://localhost:3306/springboot?allowPublicKeyRetrieval=true
hermeswing@172.17.0.1
MySQL 접속 및 데이터 확인
root@faf646b731a5:/# mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 15
Server version: 8.0.25 MySQL Community Server - GPL
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show database;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'database' at line 1
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| springboot |
| sys |
+--------------------+
5 rows in set (0.00 sec)
mysql> use springboot
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> show tables;
+----------------------+
| Tables_in_springboot |
+----------------------+
| USER |
+----------------------+
1 row in set (0.00 sec)
mysql> drop table USER;
Query OK, 0 rows affected (0.08 sec)
Docker에 Maria 설치
? docker에 mariadb 이미지 설치
$>docker pull mariadb
? Docker 컨테이너 생성
? --restart=always Docker 실행 시 같이 실행됨.
? Data backup : -v c:\Temp\data\mariadb:/var/lib/mysql
$>docker run -d -p 3306:3306 --name maria_boot -e MYSQL_ROOT_PASSWORD=1 -e MYSQL_DATABASE=springboot -e MYSQL_USER=hermeswing -e MYSQL_PASSWORD=pass -v c:\Temp\data\mariadb:/var/lib/mysql -d mariadb
? 생성된 Docker 컨테이너 확인
$>docker ps -a
? Docker 컨테이너 실행
$>docker exec -it maria_boot bash
? Maria DB 접속
? password : 1
$>mariadb -u root -p
? Maria DB 버전 확인
MariaDB [(none)]> select version();
? Docker 컨테이너 멈춤
$>docker stop maria_boot
? Docker 컨테이너 삭제
$>docker rm maria_boot
MySQL 처럼 allowPublicKeyRetrieval=true 를 붙이지 않아도 됩니다.
server.port=9090
spring.datasource.hikari.maximum-pool-size=4
spring.datasource.url=jdbc:mysql://localhost:3306/springboot
spring.datasource.username=hermeswing
spring.datasource.password=pass
위의 코드를 실행해도 그대로 실행됩니다.
root@6d01bc3192d4:/# mysql -u root -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 13
Server version: 10.6.3-MariaDB-1:10.6.3+maria~focal mariadb.org binary distribution
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> use springboot
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MariaDB [springboot]> show tables;
+----------------------+
| Tables_in_springboot |
+----------------------+
| USER |
+----------------------+
1 row in set (0.000 sec)
MariaDB [springboot]> quit
Bye
MariaDB [springboot]>
https://downloads.mariadb.com/Connectors/java
정기백업을 위한 Windows Command ( 관리자 계정으로 실행 해야 합니다. )
먼저 Docker 의 Maria Database 를 멈춤니다.
@echo off
:: 백업 경로 설정
set BACKUP_DIR=C:\Temp\Docker_Backup
set B_DATE=%DATE:~0,4%%DATE:~5,2%%DATE:~8,2%
:: 백업 폴더가 없으면 생성
if not exist "%BACKUP_DIR%" (
mkdir "%BACKUP_DIR%"
)
:: Docker 이미지 백업
set IMAGE_NAME=mariadb:latest
set IMAGE_BACKUP_PATH=%BACKUP_DIR%\maria_%B_DATE%.tar
echo Docker 이미지 백업 중: %IMAGE_BACKUP_PATH%
docker save -o %IMAGE_BACKUP_PATH% %IMAGE_NAME%
if %ERRORLEVEL% neq 0 (
echo Docker 이미지 백업 실패
exit /b 1
)
echo Docker 이미지 백업 완료: %IMAGE_BACKUP_PATH%
:: Docker 볼륨 백업
set CONTAINER_NAME=maria_boot
set VOLUME_BACKUP_PATH=%BACKUP_DIR%\maria_%B_DATE%_volume.tar
:: 컨테이너에서 볼륨 경로를 찾음
for /f "tokens=*" %%i in ('docker inspect --format "{{ range .Mounts }}{{ .Source }}{{ end }}" %CONTAINER_NAME%') do (
set VOLUME_PATH=%%i
)
if not defined VOLUME_PATH (
echo 볼륨 경로를 찾을 수 없습니다.
exit /b 1
)
echo Docker 볼륨 백업 중: %VOLUME_BACKUP_PATH%
tar -cvf %VOLUME_BACKUP_PATH% -C %VOLUME_PATH% .
if %ERRORLEVEL% neq 0 (
echo Docker 볼륨 백업 실패
exit /b 1
)
echo Docker 볼륨 백업 완료: %VOLUME_BACKUP_PATH%
echo 모든 백업이 완료되었습니다.
Maria Container를 생성 후 실행 합니다.
Volume 복원을 위한 Windows Command ( 관리자 계정으로 실행 해야 합니다. )
@echo off
if "%1"=="" (
echo ------------------------------------------------------------------------
echo Maria Database '백업 파일'이 없습니다.
echo ------------------------------------------------------------------------
echo 사용의 예
echo 1. 백업은 관리자 계정으로 실행해야 합니다.
echo 2. C:\Temp\Docker_Backup\ 폴더에 백업파일이 존재해야 합니다.
echo image 파일 : maria_20240824.tar
echo volume 파일 : maria_20240824_volume.tar
echo 3. load-maria.bat maria_20240824
goto :eof
)
:: Docker Volume 백업 경로 설정
:: Docker Container 명
set CONTAINER_NAME=maria_boot
:: 백업 파일의 위치 폴더
set BACKUP_DIR=C:\Temp\Docker_Backup
:: Volume 파일의 압축이 해제될 폴더
set VOLUME_DATA_PATH=C:\Temp\data\mariadb
if not exist "%BACKUP_DIR%\%1_volume.tar" (
echo %BACKUP_DIR%\%1_volume.tar 파일이 존재하지 않습니다.
goto :eof
)
if exist "%VOLUME_DATA_PATH%" (
echo %VOLUME_DATA_PATH% 폴더를 삭제합니다.
rmdir /S /Q %VOLUME_DATA_PATH%
echo %VOLUME_DATA_PATH% 폴더를 생성합니다.
mkdir %VOLUME_DATA_PATH%
) else (
echo %VOLUME_DATA_PATH% 폴더를 생성합니다.
mkdir %VOLUME_DATA_PATH%
)
:: Volume 파일 압축 풀기
:: Docker Volume 파일명은 파라메터명 + "_volume" 이다.
:: tar xvf C:\Temp\Docker_Backup\maria_20240824_volume.tar -C C:\Temp\data\mariadb
tar xvf %BACKUP_DIR%\%1_volume.tar -C %VOLUME_DATA_PATH%
if %ERRORLEVEL% neq 0 (
echo Docker 이미지 복원 실패
exit /b 1
)
echo Docker 볼륨 복원 완료: %VOLUME_DATA_PATH%
echo 모든 복원이 완료되었습니다.
참고 : 백기선님의 스프링 부트 개념과 활용
'Spring Framework' 카테고리의 다른 글
[Spring & Spring Boot] 스프링 JDK 버전 호환 (2) | 2024.05.11 |
---|---|
[Spring Cloud Netflix] Eureka Service 샘플 (2) | 2024.03.27 |
[Log] Log4Jdbc 설정 (0) | 2024.02.23 |
[SpringBoot] Docker에 PostgreSQL 설치 / 연결하기 (2) | 2024.02.04 |
[Redis] Docker에 Redis 설치하기 + 비밀번호 (0) | 2024.01.30 |