Spirngboot 2. X 통합 mybatis - plus + druid 다 중 데이터 원본 의 실현
70854 단어 Java
<!-- AOP-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!--MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--mybatis-plus -->
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<!--druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.22</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
프로필 추가 아래 설정:
spring:
jackson:
time-zone: GMT+8
date-format: yyyy-MM-dd HH:mm:ss
aop:
auto: true
proxy-target-class: true
datasource:
druid:
db1:
url: jdbc:mysql://ip: /db1?useSSL=false&characterEncoding=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&useUnicode=true&rewriteBatchedStatements=true
username: ****#mysql
password: ***#mysql
driver-class-name: com.mysql.cj.jdbc.Driver
initialSize: 5
minIdle: 5
maxActive: 20
db2:
url: jdbc:mysql://****/db2?useSSL=false&characterEncoding=UTF-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull&useUnicode=true&rewriteBatchedStatements=true
username: ****#mysql
password: ***#mysql
driver-class-name: com.mysql.cj.jdbc.Driver
initialSize: 5
minIdle: 5
maxActive: 20
mybatis:
type-aliases-package: com.*.*.entity #
configuration:
#
map-underscore-to-camel-case: true
mapper-locations: classpath*:/mapper/**/*.xml
# druid
druid:
config:
white-list: 127.0.0.1,loclhost
DruidConfig 설정
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
@Configuration
public class DruidConfig {
@Value("#{'${druid.config.white-list}'.split(',')}")
private List<String> whitelist;
/**
* ServletRegistrationBean
*
* @return
*/
@Bean
public ServletRegistrationBean druidServlet() {
ServletRegistrationBean reg = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
// IP
for (String ip : whitelist) {
reg.addInitParameter("allow", ip);
}
// IP ( ,deny allow)
// reg.addInitParameter("deny","127.0.0.1");
//
reg.addInitParameter("loginUsername", "**");//
reg.addInitParameter("loginPassword", "***");//
//
reg.addInitParameter("resetEnable", "false");
return reg;
}
/**
* FilterRegistrationBean
*
* @return
*/
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter(
"exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
filterRegistrationBean.addInitParameter("profileEnable", "true");
filterRegistrationBean.addInitParameter("principalCookieName", "USER_COOKIE");
filterRegistrationBean.addInitParameter("principalSessionName", "USER_SESSION");
filterRegistrationBean.addInitParameter("DruidWebStatFilter", "/*");
return filterRegistrationBean;
}
}
정의 데이터 원본 매 거 진
public enum DBTYPE {
db1("db1"),
db2("db2"),
db3("db3");
private String value;
private DBTYPE(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}
데이터 원본 컨 텍스트 정의
public class DbContextHolder {
private static final ThreadLocal contextHolder = new ThreadLocal();
public DbContextHolder() {
}
public static void setDbType(DBTYPE dbTypeEnum) {
contextHolder.set(dbTypeEnum.getValue());
}
public static String getDbType() {
return (String)contextHolder.get();
}
public static void clearDbType() {
contextHolder.remove();
}
}
동적 데이터 원본 설정
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* @program: common
* @description:
* @author: linwl
* @create: 2020-06-20 15:33
**/
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
public Object determineCurrentLookupKey()
{
return DbContextHolder.getDbType();
}
}
동적 데이터 원본 전환 클래스 정의
import db.DBTYPE;
import db.DbContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(value = -100)
@Slf4j
@Aspect
public class DataSourceSwitchAspect {
// 1
@Pointcut("execution(* com.*.mapper.db1..*.*(..))")
public void db1Aspect() {}
// 2
@Pointcut("execution(* com.*.mapper.db2..*.*(..))")
public void db2Aspect() {}
// 3
@Pointcut("execution(* com.*.mapper.db3..*.*(..))")
public void db3Aspect() {}
@Before("db1Aspect()")
public void getdb1() {
log.info(" db1 ...");
DbContextHolder.setDbType(DBTYPE.db1);
}
@Before("db2Aspect()")
public void getdb2() {
log.info(" db2 ...");
DbContextHolder.setDbType(DBTYPE.db2);
}
@Before("db3Aspect()")
public void getdb3() {
log.info(" db3 ...");
DbContextHolder.setDbType(DBTYPE.db3);
}
@After("db1Aspect()")
public void romvedb1() {
log.info(" ");
DbContextHolder.clearDbType();
}
@After("db2Aspect()")
public void romvedb2() {
log.info(" ");
DbContextHolder.clearDbType();
}
@After("db3Aspect()")
public void romvedb3() {
log.info(" ");
DbContextHolder.clearDbType();
}
}
전기의 설정 이 기본적으로 완성 되 었 습 니 다. 그 다음 에 MybatisPlus 의 설정 에 들 어가 야 합 니 다. 설정 은 다음 과 같 습 니 다.
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import db.DBTYPE;
import db.DynamicDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.StringUtils;
import javax.sql.DataSource;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
@Configuration
@MapperScan("com.***.mapper")
@EnableTransactionManagement
@Slf4j
public class MybatisPlusConfig {
@Autowired private MybatisProperties properties;
private ResourceLoader resourceLoader = new DefaultResourceLoader();
@Autowired(required = false)
private DatabaseIdProvider databaseIdProvider;
/**
* mybatis-plus
* :http://mp.baomidou.com
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor page = new PaginationInterceptor();
page.setDbType(DbType.MYSQL);
return new PaginationInterceptor();
}
@Bean(name = "db1")
@ConfigurationProperties(prefix = "spring.datasource.druid.db1")
public DataSource db1() {
return DruidDataSourceBuilder.create().build();
}
@Bean(name = "db2")
@ConfigurationProperties(prefix = "spring.datasource.druid.db2")
public DataSource db2() {
return DruidDataSourceBuilder.create().build();
}
// @Bean(name = "db3")
// @ConfigurationProperties(prefix = "spring.datasource.druid.db3")
// public DataSource db3() {
// return DruidDataSourceBuilder.create().build();
// }
/**
*
*
* @return
*/
@Bean
@Primary
public DataSource multipleDataSource(
@Qualifier("db1") DataSource db1, @Qualifier("db2") DataSource db2) {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
Map<Object, Object> targetDataSources = new HashMap<>(3);
targetDataSources.put(DBTYPE.db1.getValue(), db1);
targetDataSources.put(DBTYPE.db2.getValue(), db2);
dynamicDataSource.setTargetDataSources(targetDataSources);
dynamicDataSource.setDefaultTargetDataSource(db1);
return dynamicDataSource;
}
@Bean("sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws Exception {
try {
MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
mybatisPlus.setDataSource(multipleDataSource(db1(), db2()));
if (StringUtils.hasText(this.properties.getConfigLocation())) {
mybatisPlus.setConfigLocation(
this.resourceLoader.getResource(this.properties.getConfigLocation()));
}
mybatisPlus.setPlugins(paginationInterceptor());
MybatisConfiguration mc = new MybatisConfiguration();
mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
mybatisPlus.setConfiguration(mc);
if (this.databaseIdProvider != null) {
mybatisPlus.setDatabaseIdProvider(this.databaseIdProvider);
}
if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
mybatisPlus.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
}
if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
mybatisPlus.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
}
if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
mybatisPlus.setMapperLocations(this.properties.resolveMapperLocations());
}
return mybatisPlus.getObject();
} catch (Exception e) {
log.error(MessageFormat.format(" Mybatis :{0}!", e.getMessage()));
throw e;
}
}
}
다 중 데이터 원본 동적 전환 이 큰 성 과 를 거 두 었 습 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.