이 장을 lionsea_slave2 lionsea의 lionsea_slave1를 사용하여 이러한 데이터베이스로부터 메인 데이터베이스로 완전한 전환 스프링 부트 실시 동적 데이터 소스이다. 전용 ( "SLAVE1을") 데이터 소스를 사용하여 해당 코드에 주석을 전환 데이터베이스를 구현해야합니다.
당신이 달성하고자하는 동적 스위칭 데이터 소스는 다음과 같은 지식을 사용할 필요가
- 봄 부팅 사용자 정의 주석
- AOP 절편의 봄 부팅
- CRUD 작업을 MyBatis로
1 개 봄 부팅 메이븐 예제 프로젝트
참고 : IDEA를위한 개발 도구입니다
- 파일> 새로 만들기> 프로젝트는, 아래 그림을 선택
Spring Initializr
클릭하고 [다음] 다음 - 기입
GroupId
(패키지 이름),Artifact
(프로젝트 이름)이 될 수 있습니다. 다음을 클릭
의 groupId = com.fishpro
artifactId를 = dynamicdb을 - 선택은 따라
Spring Web Starter
전면 틱. - 프로젝트 이름이 설정됩니다
spring-boot-study-dynamicdb
.
이 의존 도입 응원단
(3 개) 핸드 오버 동적 데이터 소스
3.1 새로운 멀티 소스 데이터 주석 데이터 소스
文件 路径 (봄 부팅 학습 / 봄 부팅 - 연구 - dynamicdb / SRC / 메인 / 자바 / COM / fishpro / dynamicdb / 데이터 소스 / 주석 / DataSource.java)
/**
* 多数据源注解
* 在方法名上加入 DataSource('名称')
*
* @author fishpro
* */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface DataSource {
String value() default "";
}
3.2 이상의 데이터 소스를 절환 콘텍스트 생성 DynamicContextHolder
/**
* 多数据源上下文
*
*/
public class DynamicContextHolder {
@SuppressWarnings("unchecked")
private static final ThreadLocal<Deque<String>> CONTEXT_HOLDER = new ThreadLocal() {
@Override
protected Object initialValue() {
return new ArrayDeque();
}
};
/**
* 获得当前线程数据源
*
* @return 数据源名称
*/
public static String getDataSource() {
return CONTEXT_HOLDER.get().peek();
}
/**
* 设置当前线程数据源
*
* @param dataSource 数据源名称
*/
public static void setDataSource(String dataSource) {
CONTEXT_HOLDER.get().push(dataSource);
}
/**
* 清空当前线程数据源
*/
public static void clearDataSource() {
Deque<String> deque = CONTEXT_HOLDER.get();
deque.poll();
if (deque.isEmpty()) {
CONTEXT_HOLDER.remove();
}
}
}
3.3 다중 소스 데이터 처리부 클래스 만들기
클래스 주석 포인트 AOP 처리 및 이벤트 처리는 핸드 오버를 완료하기 위해, (데이터 소스를 전환합니다) 여러 데이터 소스의 지금까지의 주요 작품을 멀티 소스 데이터 처리부를 지정 만듭니다.
/**
* 多数据源,切面处理类
*
*/
@Aspect
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DataSourceAspect {
protected Logger logger = LoggerFactory.getLogger(getClass());
/**
* 切面点 指定注解
* */
@Pointcut("@annotation(com.fishpro.dynamicdb.datasource.annotation.DataSource) " +
"|| @within(com.fishpro.dynamicdb.datasource.annotation.DataSource)")
public void dataSourcePointCut() {
}
/**
* 拦截方法指定为 dataSourcePointCut
* */
@Around("dataSourcePointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Class targetClass = point.getTarget().getClass();
Method method = signature.getMethod();
DataSource targetDataSource = (DataSource)targetClass.getAnnotation(DataSource.class);
DataSource methodDataSource = method.getAnnotation(DataSource.class);
if(targetDataSource != null || methodDataSource != null){
String value;
if(methodDataSource != null){
value = methodDataSource.value();
}else {
value = targetDataSource.value();
}
DynamicContextHolder.setDataSource(value);
logger.debug("set datasource is {}", value);
}
try {
return point.proceed();
} finally {
DynamicContextHolder.clearDataSource();
logger.debug("clean datasource");
}
}
}
3.4 데이터 소스를 절환
AOP 방법은 방법 주석 @DataSource을 가로 챌 때 시행하는 방법, 지정된 데이터 소스를 수행 할 필요가 우리가 데이터 소스 연결 풀 알리의 드루이드를 연결 풀링을 사용하여 여기에있다. 이것은 우리가 사용자 정의 연결 풀을 개발해야해야합니다. AOP 설치 정보 동적 스위칭 대상 데이터 소스를 달성하기 위해 인터 라우팅 데이터베이스를 리셋한다.
3.4.1 사용자는 풀 등록 링크
노드 application.yml 배치
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ry?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: 123
initial-size: 10
max-active: 100
min-idle: 10
max-wait: 60000
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
#Oracle需要打开注释
#validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
stat-view-servlet:
enabled: true
url-pattern: /druid/*
#login-username: admin
#login-password: admin
filter:
stat:
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: false
wall:
config:
multi-statement-allow: true
/**
* 多数据源主数据源属性
*
*/
public class DataSourceProperties {
private String driverClassName;
private String url;
private String username;
private String password;
/**
* Druid默认参数
*/
private int initialSize = 2;
private int maxActive = 10;
private int minIdle = -1;
private long maxWait = 60 * 1000L;
private long timeBetweenEvictionRunsMillis = 60 * 1000L;
private long minEvictableIdleTimeMillis = 1000L * 60L * 30L;
private long maxEvictableIdleTimeMillis = 1000L * 60L * 60L * 7;
private String validationQuery = "select 1";
private int validationQueryTimeout = -1;
private boolean testOnBorrow = false;
private boolean testOnReturn = false;
private boolean testWhileIdle = true;
private boolean poolPreparedStatements = false;
private int maxOpenPreparedStatements = -1;
private boolean sharePreparedStatements = false;
private String filters = "stat,wall";
/* 省略自动化生成部分 */
}
데이터 소스 속성 클래스에서 3.4.2 여러 데이터 소스
application.xml에 여러 데이터베이스에 대한 지원과 같이 표현
dynamic:
datasource:
#slave1 slave2 数据源已测试
slave1:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/lionsea_slave1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: 123456
slave2:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/lionsea_slave2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: 123456
slave3:
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
url: jdbc:sqlserver://localhost:1433;DatabaseName=renren_security
username: sa
password: 123456
slave4:
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://localhost:5432/renren_security
username: renren
password: 123456
복수의 데이터 소스는, 클래스를 나타내는 소스 애플리케이션 속성의 데이터는 동적 노드에 구성된
/**
* 多数据源属性 在application中表示为以 dynamic 为节点的配置
*
*/
@ConfigurationProperties(prefix = "dynamic")
public class DynamicDataSourceProperties {
private Map<String, DataSourceProperties> datasource = new LinkedHashMap<>();
public Map<String, DataSourceProperties> getDatasource() {
return datasource;
}
public void setDatasource(Map<String, DataSourceProperties> datasource) {
this.datasource = datasource;
}
}
3.4.3 동적 데이터 소스 팩토리 클래스를 설정
동적 데이터 소스 연결 풀 사제를 만들기위한 동적 데이터 소스 팩토리 클래스를 구축
/**
* DruidDataSource
*
*/
public class DynamicDataSourceFactory {
/**
* 通过自定义建立 Druid的数据源
* */
public static DruidDataSource buildDruidDataSource(DataSourceProperties properties) {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(properties.getDriverClassName());
druidDataSource.setUrl(properties.getUrl());
druidDataSource.setUsername(properties.getUsername());
druidDataSource.setPassword(properties.getPassword());
druidDataSource.setInitialSize(properties.getInitialSize());
druidDataSource.setMaxActive(properties.getMaxActive());
druidDataSource.setMinIdle(properties.getMinIdle());
druidDataSource.setMaxWait(properties.getMaxWait());
druidDataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
druidDataSource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis());
druidDataSource.setMaxEvictableIdleTimeMillis(properties.getMaxEvictableIdleTimeMillis());
druidDataSource.setValidationQuery(properties.getValidationQuery());
druidDataSource.setValidationQueryTimeout(properties.getValidationQueryTimeout());
druidDataSource.setTestOnBorrow(properties.isTestOnBorrow());
druidDataSource.setTestOnReturn(properties.isTestOnReturn());
druidDataSource.setPoolPreparedStatements(properties.isPoolPreparedStatements());
druidDataSource.setMaxOpenPreparedStatements(properties.getMaxOpenPreparedStatements());
druidDataSource.setSharePreparedStatements(properties.isSharePreparedStatements());
try {
druidDataSource.setFilters(properties.getFilters());
druidDataSource.init();
} catch (SQLException e) {
e.printStackTrace();
}
return druidDataSource;
}
}
3.4.3 구성 여러 구성 클래스 데이터 소스
/**
* 配置多数据源
*
*/
@Configuration
@EnableConfigurationProperties(DynamicDataSourceProperties.class)
public class DynamicDataSourceConfig {
@Autowired
private DynamicDataSourceProperties properties;
@Bean
@ConfigurationProperties(prefix = "spring.datasource.druid")
public DataSourceProperties dataSourceProperties() {
return new DataSourceProperties();
}
@Bean
public DynamicDataSource dynamicDataSource(DataSourceProperties dataSourceProperties) {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
dynamicDataSource.setTargetDataSources(getDynamicDataSource());
//默认数据源
DruidDataSource defaultDataSource = DynamicDataSourceFactory.buildDruidDataSource(dataSourceProperties);
dynamicDataSource.setDefaultTargetDataSource(defaultDataSource);
return dynamicDataSource;
}
private Map<Object, Object> getDynamicDataSource(){
Map<String, DataSourceProperties> dataSourcePropertiesMap = properties.getDatasource();
Map<Object, Object> targetDataSources = new HashMap<>(dataSourcePropertiesMap.size());
dataSourcePropertiesMap.forEach((k, v) -> {
DruidDataSource druidDataSource = DynamicDataSourceFactory.buildDruidDataSource(v);
targetDataSources.put(k, druidDataSource);
});
return targetDataSources;
}
}
3.5 테스트 여러 데이터 소스
CRUD의 MyBatis로의 설립을 기반으로 테스트를위한 봄 부팅 테스트 클래스를 사용합니다.
라이브러리 2에서, 세 새 마스터 데이터 라이브러리 3.5.1
두 라이브러리에서 세 개의 새로운 마스터 데이터베이스 데이터, 아래의 새 데이터베이스 테이블의 각
DROP TABLE IF EXISTS `demo_test`;
CREATE TABLE `demo_test` (
`id` bigint(20) NOT NULL,
`name` varchar(255) NOT NULL,
`status` tinyint(4) DEFAULT NULL,
`is_deleted` tinyint(4) DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`create_user_id` bigint(20) DEFAULT NULL,
`age` bigint(20) DEFAULT NULL,
`content` text,
`body` longtext,
`title` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_name` (`name`) USING BTREE,
KEY `idx_title` (`title`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
3.5.2 CRUD의 기본 MyBatis로를 확립
여기 CRUD를 (수동)는 DAO / 도메인 / 서비스 / IMPL 포함 제조 주 사용 코드 생성기
/domain/DemoTestDO.java
public class DemoTestDO implements Serializable {
private static final long serialVersionUID = 1L;
//
private Long id;
//
private String name;
//
private Integer status;
//
private Integer isDeleted;
//
private Date createTime;
//
private Long createUserId;
//
private Long age;
//
private String content;
//
private String body;
//
private String title;
//省略自动生成的部分
}
/dao/DemoTestDao.java
@Mapper
public interface DemoTestDao {
DemoTestDO get(Long id);
List<DemoTestDO> list(Map<String, Object> map);
int count(Map<String, Object> map);
int save(DemoTestDO demoTest);
int update(DemoTestDO demoTest);
int remove(Long id);
int batchRemove(Long[] ids);
}
특히 참조 프로젝트 github에 소스 코드를 다운로드
3.5.3 쓰기 테스트 코드
시험 방법 동적 클래스 코드
@Service
//@DataSource("slave1")
public class DynamicDataSourceTestService {
@Autowired
private DemoTestDao demoTestDao;
@Transactional
public void updateDemoTest(Long id){
DemoTestDO user = new DemoTestDO();
user.setId(id);
user.setTitle("13500000000");
demoTestDao.update(user);
}
@Transactional
@DataSource("slave1")
public void updateDemoTestBySlave1(Long id){
DemoTestDO user = new DemoTestDO();
user.setId(id);
user.setTitle("13500000001");
demoTestDao.update(user);
}
@DataSource("slave2")
@Transactional
public void updateDemoTestBySlave2(Long id){
DemoTestDO user = new DemoTestDO();
user.setId(id);
user.setTitle("13500000002");
demoTestDao.update(user);
//测试事物
// int i = 1/0;
}
}
동적 테스트 코드
@RunWith(SpringRunner.class)
@SpringBootTest
public class DynamicdbApplicationTests {
@Autowired
private DynamicDataSourceTestService dynamicDataSourceTestService;
/**
* 观察三个数据源中的数据是否正确
* */
@Test
public void testDaynamicDataSource(){
Long id = 1L;
dynamicDataSourceTestService.updateDemoTest(id);
dynamicDataSourceTestService.updateDemoTestBySlave1(id);
dynamicDataSourceTestService.updateDemoTestBySlave2(id);
}
}
3.6 테스트
오른쪽 DynamicDataSourceTest 실행 실행 DynamicDataSourceTest
默认数据库操作成功
slave1数据库操作成功
slave2数据库操作成功
Process finished with exit code 0