springboot+my batis+druid 를 통 해 동적 데이터 원본 설정

1.데이터베이스 구축 및 표
1.데이터베이스 demo 1 user 표 한 장 넣 기

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'aa');
INSERT INTO `user` VALUES ('2', 'bb');
2.데이터베이스 demo 2 role 표 한 장 넣 기

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES ('1', 'CC');
INSERT INTO `role` VALUES ('2', 'DD');
2.pom.xml 도입 패키지

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<!-- aop -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<!-- alibaba druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!-- dynamic-->
<dependency>
<groupId>com.typesafe.dynamicdatasource</groupId>
<artifactId>dynamic-data-source_2.11</artifactId>
</dependency>
3.generator 플러그 인 으로 user,role 두 장의 표 의 실체 류,mapper.자바,mapper.xml 를 생 성 합 니 다.

User.java
Role.java
UserMapper.java
RoleMapper.java
UserMapper.xml
RoleMapper.xml
4.application.yml 설정

server:
port: 8088
mybatis:
mapper-locations: classpath:mapper/*.xml
spring:
datasource:
db1:
url: jdbc:mysql://localhost:3306/demo1?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
#   
driver-class-name: com.mysql.cj.jdbc.Driver
#     
initial-size: 5
#     
min-idle: 5
#     
max-active: 20
#      
max-wait: 60000
#             ,           ,     
time-between-eviction-runs-millis: 60000
#                 ,     
min-evictable-idle-time-millis: 300000
#            ,MYSQL select 1
validation-query: SELECT 1 FROM DUAL
#     ,testOnBorrow testOnReturn            ,       。        testWhileIdle  
test-while-idle: true
test-on-borrow: false
test-on-return: false
#  PSCache,         PSCache  
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
#         filters,       sql    ,‘wall'     ,   filter     
filters: stat,wall
#  connectproperties     mergesql  : sql  
connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
#    DruidDataSource
useGlobalDataSourceStat: true
db2:
url: jdbc:mysql://localhost:3306/demo2?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
#   
driver-class-name: com.mysql.cj.jdbc.Driver
#     
initial-size: 5
#     
min-idle: 5
#     
max-active: 20
#      
max-wait: 60000
#             ,           ,     
time-between-eviction-runs-millis: 60000
#                 ,     
min-evictable-idle-time-millis: 300000
#            ,MYSQL select 1
validation-query: SELECT 1 FROM DUAL
#     ,testOnBorrow testOnReturn            ,       。        testWhileIdle  
test-while-idle: true
test-on-borrow: false
test-on-return: false
#  PSCache,         PSCache  
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
#         filters,       sql    ,‘wall'     ,   filter     
filters: stat,wall
#  connectproperties     mergesql  : sql  
connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
#    DruidDataSource
useGlobalDataSourceStat: true
5.시작 클래스 스 캔 mapper.자바 파일

@SpringBootApplication
@MapperScan("com.example.demo.dao")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
6.DataSourceConfig 를 정의 하고 application.yml 의 설정 을 DataSource 에 가 져 오고 bean 에 주입 합 니 다.

@Configuration
public class DataSourceConfig {
//          
@Primary
@Bean(name="datasource1")
@ConfigurationProperties("spring.datasource.db1")
public DataSource dataSource1(){
return new DruidDataSource();
}
//          
@Bean(name="datasource2")
@ConfigurationProperties("spring.datasource.db2")
public DataSource dataSource2(){
return new DruidDataSource();
}
//             
@Bean(name="dynamicDataSource")
public DataSource dynamicDataSource(){
DynamicDataSource dynamicDatasource=new DynamicDataSource();
//       
dynamicDatasource.setDefaultTargetDataSource(dataSource1());
//      
Map<Object,Object> dsMap=new HashMap<>();
dsMap.put("datasource1",dataSource1());
dsMap.put("datasource2",dataSource2());
//            
dynamicDatasource.setTargetDataSources(dsMap);
return dynamicDatasource;
}
}
7.동적 데이터 원본 전환 클래스 DynamicDataSource ContextHolder 정의

public class DynamicDataSourceContextHolder {
private static final ThreadLocal<String> contextHolder=new ThreadLocal<>();
//       
public static void setDB(String dbType){
contextHolder.set(dbType);
}
//       
public static String getDB(){
return contextHolder.get();
}
//      
public static void clearDB(){
contextHolder.remove();
}
}
8.동적 데이터 원본 류 DynamicDataSource 가 져 오기 정의

public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceContextHolder.getDB();
}
}
9.my batis 설정 클래스 를 정의 하고 DynamicDataSource 를 SqlSession Factory Bean 에 넣 습 니 다.

@EnableTransactionManagement
@Configuration
public class MyBatisConfig {
@Resource(name = "dynamicDataSource")
private DataSource dynamicDataSource;
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dynamicDataSource);//      bean   sqlsessionfactory
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean
public PlatformTransactionManager platformTransactionManager() {
return new DataSourceTransactionManager(dynamicDataSource);
}
}
10.데이터 원본 전환 에 사용 할 주 해 를 정의 합 니 다.TargetDataSource

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetDataSource {
String value() default "datasource1";
}
11.절단면 DynamicDataSourceAspect 를 정의 하여 주 해 를 차단 하고 데이터 원본 전환 기능 을 수행 합 니 다.

@Aspect
@Component
public class DynamicDataSourceAspect {
@Before("@annotation(targetDataSource)")
public void beforeSwitchDS(JoinPoint point,TargetDataSource targetDataSource){
DynamicDataSourceContextHolder.setDB(targetDataSource.value());
}
@After("@annotation(targetDataSource)")
public void afterSwitchDS(JoinPoint point,TargetDataSource targetDataSource){
DynamicDataSourceContextHolder.clearDB();
}
}
12.테스트 클래스 테스트

@RestController
public class Test {
@Autowired
private RoleMapper roleMapper;
@Autowired
private UserMapper userMapper;
//   TargetDataSource  ,        , datasource1
@RequestMapping("/ds1")
public String selectDataSource1(){
return userMapper.selectByPrimaryKey(1).toString();
}
//     ,           datasource2
@RequestMapping("/ds2")
@TargetDataSource("datasource2")
public String selectDataSource2(){
return roleMapper.selectByPrimaryKey(1).toString();
}
}
테스트
1.입력http://localhost:8088/ds1되돌아오다


2.입력http://localhost:8088/ds2되돌아오다


결론:두 번 의 요청 이 각각 다른 데이터베이스 에서 데 이 터 를 가 져 왔 습 니 다.다 중 데이터 원본 설정 이 성공 하 였 습 니 다!
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기