initial import

main
semin.baek 11 months ago
parent 012f690fc6
commit 2f93a79757

@ -0,0 +1,44 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.4.3'
id 'io.spring.dependency-management' version '1.1.7'
}
group = 'com.bsmlab.dfx'
version = '0.0.1-SNAPSHOT'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.4'
compileOnly 'org.projectlombok:lombok'
implementation 'com.h2database:h2'
implementation 'com.microsoft.sqlserver:mssql-jdbc'
implementation 'com.mysql:mysql-connector-j'
implementation 'com.oracle.database.jdbc:ojdbc11'
implementation 'org.mariadb.jdbc:mariadb-java-client'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter-test:3.0.4'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
tasks.named('test') {
useJUnitPlatform()
}

252
gradlew vendored

@ -0,0 +1,252 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

94
gradlew.bat vendored

@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

@ -0,0 +1 @@
rootProject.name = 'agent'

@ -0,0 +1,216 @@
### ✅ **Spring Boot에서 동적으로 N개의 데이터소스를 추가하고, 특정 이름에 따른 Connection Pool로 관리하기**
> 🚀 **요구사항 업데이트:**
> 1. **각 데이터소스는 특정한 이름(`dataSourceName`)으로 관리**.
> 2. **각 데이터소스마다 개별적인 Connection Pool을 사용**.
> 3. **동적으로 데이터소스를 추가할 수 있어야 함**.
> 4. **각 데이터소스는 `TransactionManager`에 의해 관리됨**.
> 5. **MyBatis와 연동**.
---
## **🔹 1. 데이터소스를 Connection Pool로 관리하는 `DynamicRoutingDataSource` 구현**
각 데이터소스는 **Connection Pool(DBCP2)를 사용하여 동적으로 추가**하며,
각 요청 시 **ThreadLocal을 이용하여 특정 데이터소스를 선택**할 수 있도록 `AbstractRoutingDataSource`를 활용합니다.
📄 **`DynamicRoutingDataSource.java`**
```java
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
private final Map<Object, Object> dataSourceMap = new ConcurrentHashMap<>();
@Override
protected Object determineCurrentLookupKey() {
return contextHolder.get();
}
public void setDataSource(String dataSourceName) {
contextHolder.set(dataSourceName);
}
public void clearDataSource() {
contextHolder.remove();
}
public void addDataSource(String name, DataSource dataSource) {
dataSourceMap.put(name, dataSource);
super.setTargetDataSources(dataSourceMap);
super.afterPropertiesSet();
}
public Map<Object, Object> getDataSourceMap() {
return dataSourceMap;
}
}
```
**기능:**
- `setDataSource("dataSourceName")`을 호출하면 **해당 데이터소스를 선택**하여 사용.
- `addDataSource("dataSourceName", DataSource)`을 통해 **새로운 데이터소스를 동적으로 추가 가능**.
- `ConcurrentHashMap`을 사용하여 **Connection Pool을 효율적으로 관리**.
---
## **🔹 2. 데이터소스 설정 및 Connection Pool 관리**
각 데이터소스는 **DBCP2 커넥션 풀**을 사용하여 생성됩니다.
📄 **`DynamicDataSourceConfig.java`**
```java
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionTemplate;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
@MapperScan(basePackages = "com.example.mapper", sqlSessionTemplateRef = "dynamicSqlSessionTemplate")
public class DynamicDataSourceConfig {
@Bean
public DynamicRoutingDataSource dynamicRoutingDataSource() {
DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource();
// 기본 데이터소스 등록
DataSource defaultDataSource = createDataSource("jdbc:mysql://localhost:3306/default_db", "root", "password");
dynamicRoutingDataSource.addDataSource("default", defaultDataSource);
return dynamicRoutingDataSource;
}
@Bean
public DataSourceTransactionManager transactionManager(DynamicRoutingDataSource dynamicRoutingDataSource) {
return new DataSourceTransactionManager(dynamicRoutingDataSource);
}
@Bean
public SqlSessionFactory sqlSessionFactory(DynamicRoutingDataSource dynamicRoutingDataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dynamicRoutingDataSource);
return sessionFactory.getObject();
}
@Bean
public SqlSessionTemplate dynamicSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
private DataSource createDataSource(String url, String username, String password) {
// DBCP2 Connection Pool 사용
PooledDataSource dataSource = new PooledDataSource();
dataSource.setDriver("com.mysql.cj.jdbc.Driver");
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
}
```
**기능:**
- `createDataSource()`를 사용하여 **각각의 데이터소스를 DBCP2 기반 Connection Pool로 생성**.
- `dynamicRoutingDataSource.addDataSource("default", defaultDataSource);`를 호출하여 기본 데이터소스를 등록.
---
## **🔹 3. 새로운 데이터소스를 동적으로 추가하는 서비스**
📄 **`DynamicDataSourceService.java`**
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
@Service
public class DynamicDataSourceService {
@Autowired
private DynamicRoutingDataSource dynamicRoutingDataSource;
public void addNewDataSource(String dataSourceName, String url, String username, String password) {
DataSource newDataSource = createDataSource(url, username, password);
dynamicRoutingDataSource.addDataSource(dataSourceName, newDataSource);
System.out.println("✅ 새로운 데이터소스 추가됨: " + dataSourceName);
}
private DataSource createDataSource(String url, String username, String password) {
PooledDataSource dataSource = new PooledDataSource();
dataSource.setDriver("com.mysql.cj.jdbc.Driver");
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
}
```
**기능:**
- `addNewDataSource("newDB", "jdbc:mysql://localhost:3306/new_db", "user", "pass")`을 호출하면 **새로운 데이터소스를 동적으로 추가**.
- `dynamicRoutingDataSource.addDataSource(dataSourceName, newDataSource)`을 사용하여 **데이터소스를 관리하는 Connection Pool에 추가**.
---
## **🔹 4. 특정 데이터소스를 선택하여 트랜잭션 처리**
📄 **`UserService.java`**
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public void fetchUsersFromDefault() {
DynamicRoutingDataSource.setDataSource("default");
System.out.println("🔹 Default DB에서 데이터 조회");
System.out.println(userMapper.findAll());
}
@Transactional
public void fetchUsersFromNewDB() {
DynamicRoutingDataSource.setDataSource("newDB");
System.out.println("🔹 New DB에서 데이터 조회");
System.out.println(userMapper.findAll());
}
}
```
📄 **`UserMapper.java`**
```java
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users")
List<Map<String, Object>> findAll();
}
```
**기능:**
- `DynamicRoutingDataSource.setDataSource("newDB")`를 호출하면 **특정 데이터소스를 선택**.
- MyBatis에서 **선택된 데이터소스를 기반으로 SQL 실행**.
- `@Transactional`을 사용하여 **선택된 데이터소스에서 트랜잭션 처리** 가능.
---
## ✅ **최종 정리**
| 기능 | 코드 |
|------|------|
| **동적으로 데이터소스 변경** | `DynamicRoutingDataSource.setDataSource("dataSourceName")` |
| **새로운 데이터소스 추가** | `dynamicDataSourceService.addNewDataSource("newDB", "url", "user", "pass")` |
| **Connection Pool 관리** | `PooledDataSource` (MyBatis DBCP2 사용) |
| **트랜잭션 관리** | `@Transactional` 사용 |
| **MyBatis 연동** | `SqlSessionFactory` + `SqlSessionTemplate` 사용 |
**이제 애플리케이션 실행 중에도 N개의 데이터소스를 추가하고, Connection Pool로 관리하며, MyBatis와 연동하여 사용할 수 있습니다!** 🚀

@ -0,0 +1,12 @@
datasource:
dfcms:
driverClassName: org.postgresql.Driver
url: jdbc:postgresql://bsm-lab.com:5432/defree?currentSchema=DFCMS
username: defreeadmin
password: qortpals1!
mochastory:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://bsm-lab.com:3306/MOCHASTORY?allowPublicKeyRetrieval=true
username: MOCHASTORY
password: MOCHASTORY

@ -0,0 +1,6 @@
CREATE TABLE TB_HOST (
HOST_ID VARCHAR(512) NOT NULL
, HOST_NAME VARCHAR(1024) NOT NULL
, HOST_TYPE VARCHAR(64) NOT NULL
, PRIMARY KEY (HOST_ID)
);

@ -0,0 +1,13 @@
package com.bsmlab.dfx.agent;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DfxAgentApplication {
public static void main(String[] args) {
SpringApplication.run(DfxAgentApplication.class, args);
}
}

@ -0,0 +1,37 @@
package com.bsmlab.dfx.agent.config;
import com.fasterxml.jackson.databind.DatabindException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.io.support.ResourcePropertySource;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.util.Map;
@Slf4j
@Component
public class DfxAgengConfiguration {
private String settingFilePath;
public void loadConfiguraion() {
//setting.file=D:\projects\bsm-lab\dfx\run\dfxagent.json
String embeddedDbFileDirectory = System.getProperty("embedded.db.file.directory");
this.settingFilePath = System.getProperty("setting.file");
try {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> settingMap = mapper.readValue(new File(this.settingFilePath), Map.class);
} catch (DatabindException e) {
log.error("cannot parse a setting file. {}", this.settingFilePath, e);
} catch (IOException e) {
log.error("cannot found a setting file. {}", this.settingFilePath);
log.error("-Dsetting.file=[file path] needed.");
}
}
public String getSettingFilePath() {
return this.settingFilePath;
}
}

@ -0,0 +1,57 @@
package com.bsmlab.dfx.agent.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
@MapperScan(basePackages = "com.bsmlab.dfx.agent", sqlSessionTemplateRef = "dynamicSqlSessionTemplate")
public class DynamicDataSourceConfig {
@Bean
public DynamicRoutingDataSource dynamicRoutingDataSource() {
DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource();
// 기본 데이터소스 등록
DataSource defaultDataSource = createDataSource("jdbc:mysql://localhost:3306/default_db", "root", "password");
dynamicRoutingDataSource.addDataSource("default", defaultDataSource);
return dynamicRoutingDataSource;
}
@Bean
public DataSourceTransactionManager transactionManager(DynamicRoutingDataSource dynamicRoutingDataSource) {
return new DataSourceTransactionManager(dynamicRoutingDataSource);
}
@Bean
public SqlSessionFactory sqlSessionFactory(DynamicRoutingDataSource dynamicRoutingDataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dynamicRoutingDataSource);
return sessionFactory.getObject();
}
@Bean
public SqlSessionTemplate dynamicSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
private DataSource createDataSource(String url, String username, String password) {
// DBCP2 Connection Pool 사용
PooledDataSource dataSource = new PooledDataSource();
dataSource.setDriver("com.mysql.cj.jdbc.Driver");
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
}

@ -0,0 +1,28 @@
package com.bsmlab.dfx.agent.config;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
@Service
public class DynamicDataSourceService {
@Autowired
private DynamicRoutingDataSource dynamicRoutingDataSource;
public void addNewDataSource(String dataSourceName, String driver, String url, String username, String password) {
DataSource newDataSource = createDataSource(driver, url, username, password);
dynamicRoutingDataSource.addDataSource(dataSourceName, newDataSource);
System.out.println("✅ 새로운 데이터소스 추가됨: " + dataSourceName);
}
private DataSource createDataSource(String driver, String url, String username, String password) {
PooledDataSource dataSource = new PooledDataSource();
dataSource.setDriver(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
}

@ -0,0 +1,35 @@
package com.bsmlab.dfx.agent.config;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
private final Map<Object, Object> dataSourceMap = new ConcurrentHashMap<>();
@Override
protected Object determineCurrentLookupKey() {
return contextHolder.get();
}
public void setDataSource(String dataSourceName) {
contextHolder.set(dataSourceName);
}
public void clearDataSource() {
contextHolder.remove();
}
public void addDataSource(String name, DataSource dataSource) {
dataSourceMap.put(name, dataSource);
super.setTargetDataSources(dataSourceMap);
super.afterPropertiesSet();
}
public Map<Object, Object> getDataSourceMap() {
return dataSourceMap;
}
}

@ -0,0 +1,41 @@
package com.bsmlab.dfx.agent.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
@Slf4j
@Component
public class EmbeddedDbInitializer {
private static final String DB_SOURCE_FILE_PATH = "./storages/dfxagent.mv.db";
public void copyEmbeddedDbFileIfNotExists() {
log.debug("run");
String embeddedDbFileDirectory = System.getProperty("embedded.db.file.directory");
File targetDirectory = new File(embeddedDbFileDirectory);
if(!targetDirectory.exists()) {
targetDirectory = new File(System.getProperty("user.home"));
}
File targetFile = new File(targetDirectory.getAbsoluteFile() + "/dfxagent.mv.db");
log.debug("embeddedDbFilePath: {}", embeddedDbFileDirectory);
if(!targetFile.exists()) {
try {
InputStream inputStream = new ClassPathResource(DB_SOURCE_FILE_PATH).getInputStream();
log.debug("embedded db file copy from {} to {}", DB_SOURCE_FILE_PATH, embeddedDbFileDirectory);
Files.copy(inputStream, Paths.get(targetFile.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING);
}
catch (IOException e) {
log.error("cannot make Embedded DB files. exit application.");
System.exit(0);
}
}
}
}

@ -0,0 +1,25 @@
package com.bsmlab.dfx.agent.config;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Slf4j
@RequiredArgsConstructor
@Component
public class StartupRunner implements ApplicationRunner {
private final EmbeddedDbInitializer embeddedDbInitializer;
@Override
public void run(ApplicationArguments args) throws Exception {
log.debug("run");
//TODO 1. dfxagent.yml 로드 및 설정 관리자에 저장
//TODO 2. embedded db 체크 및 생성
embeddedDbInitializer.copyEmbeddedDbFileIfNotExists();
//TODO 3. dfxagent.yml 을 기반으로 데이터소스 및 커넥션 풀 생성
//TODO 4. Worker 쓰레드 생성
}
}

@ -0,0 +1,12 @@
package com.bsmlab.dfx.agent.config;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users")
List<Map<String, Object>> findAll();
}

@ -0,0 +1,25 @@
package com.bsmlab.dfx.agent.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public void fetchUsersFromDefault() {
DynamicRoutingDataSource.setDataSource("default");
System.out.println("🔹 Default DB에서 데이터 조회");
System.out.println(userMapper.findAll());
}
@Transactional
public void fetchUsersFromNewDB() {
DynamicRoutingDataSource.setDataSource("newDB");
System.out.println("🔹 New DB에서 데이터 조회");
System.out.println(userMapper.findAll());
}
}

@ -0,0 +1 @@
spring.application.name=DFX Agent

@ -0,0 +1,12 @@
spring:
application:
name: DFX Agent
h2:
console: true
path: /dfxagent-db-console
datasource:
driverClassName: org.h2.driver
url: jdbc:h2:classpath:/storages/dfxagent
username: smbaek
password: qortpals1!

@ -0,0 +1,13 @@
package com.bsmlab.dfx.agent;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DfxAgentApplicationTests {
@Test
void contextLoads() {
}
}
Loading…
Cancel
Save