当前位置:网站首页>Shardingsphere dynamic data source
Shardingsphere dynamic data source
2022-07-03 03:32:00 【Today, the flowers are sad】
Used in the project mybatis-plus, Multi data source switching uses dynamic-datasource-spring-boot-starter, Just add @DS Annotation can be switched , Very convenient , But as the business gets more complex , More and more data , It involves reading and writing separation, database and table , We choose shardingsphere No code intrusion solution , take shardingsphere hand dynamic-datasource management , It is convenient to switch data sources and use shardingsphere Read write separation, sub database, sub table and other functions .
pom Introduce dependencies
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.1.1</version><!-- This version is recommended , The advanced version removes some parameters -->
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-namespace</artifactId>
<version>4.0.0-RC1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>Dynamic data source configuration
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.provider.AbstractDataSourceProvider;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceAutoConfiguration;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import org.apache.shardingsphere.shardingjdbc.jdbc.adapter.AbstractDataSourceAdapter;
import org.apache.shardingsphere.shardingjdbc.spring.boot.SpringBootConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Map;
/**
* Dynamic data source configuration :
*
* Use {@link com.baomidou.dynamic.datasource.annotation.DS} annotation , Switch data source
*
* <code>@DS(DataSourceConfiguration.SHARDING_DATA_SOURCE_NAME)</code>
*
* @author ws
* @date 2022/6/21 15:19
*/
@Configuration
@AutoConfigureBefore({DynamicDataSourceAutoConfiguration.class,
SpringBootConfiguration.class})
public class DataSourceConfiguration {
/**
* Name of the data source of the split table
*/
private static final String SHARDING_DATA_SOURCE_NAME = "shardingjdbc";
/**
* Dynamic data source configuration item
*/
@Autowired
private DynamicDataSourceProperties properties;
/**
* shardingjdbc There are four data sources , Different data sources need to be injected according to the business
*
* <p>1. No slicing is used , The name of desensitization ( Default ): shardingDataSource;
* <p>2. Master slave data source : masterSlaveDataSource;
* <p>3. Desensitization data source :encryptDataSource;
* <p>4. Shadow data source :shadowDataSource
*
*/
@Lazy
@Resource(name = "shardingDataSource")
AbstractDataSourceAdapter shardingDataSource;
@Bean
public DynamicDataSourceProvider dynamicDataSourceProvider() {
Map<String, DataSourceProperty> datasourceMap = properties.getDatasource();
return new AbstractDataSourceProvider() {
@Override
public Map<String, DataSource> loadDataSources() {
Map<String, DataSource> dataSourceMap = createDataSourceMap(datasourceMap);
// take shardingjdbc Managed data sources are also managed by dynamic data sources
dataSourceMap.put(SHARDING_DATA_SOURCE_NAME, shardingDataSource);
return dataSourceMap;
}
};
}
/**
* Set the dynamic data source as the preferred
* When spring When there are multiple data sources , Automatic injection is the preferred object
* After setting as the primary data source , You can support shardingjdbc Native configuration
*
* @return
*/
@Primary
@Bean
public DataSource dataSource(DynamicDataSourceProvider dynamicDataSourceProvider) {
DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource();
// dataSource.setPrimary(properties.getPrimary());
// Set up here sharding The managed data source is the default data source ,
// If other settings are set, then yml File configuration primary: data source
dataSource.setPrimary(SHARDING_DATA_SOURCE_NAME);
dataSource.setStrict(properties.getStrict());
dataSource.setStrategy(properties.getStrategy());
dataSource.setProvider(dynamicDataSourceProvider);
dataSource.setP6spy(properties.getP6spy());
dataSource.setSeata(properties.getSeata());
return dataSource;
}
}
application.yml, here shardingsphere Configured read / write separation policy
server:
port: 9099
servlet:
context-path: /quarant/server
spring:
shardingsphere:
datasource:
# Configure real data sources
names: ds0,ds1
ds0:
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://172.18.11.9:3306/quarant_db?serverTimezone=Asia/Shanghai&useLegacyDatetimeCode=false&useSSL=false&nullNamePatternMatchesAll=true&useUnicode=true&characterEncoding=UTF-8
username: root
password: [email protected]
type: com.zaxxer.hikari.HikariDataSource
initialSize: 5
minIdle: 10
maxActive: 50
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
maxEvictableIdleTimeMillis: 900000
validationQuery: SELECT 1 FROM DUAL
ds1:
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://172.18.11.9:3306/quarant_db1?serverTimezone=Asia/Shanghai&useLegacyDatetimeCode=false&useSSL=false&nullNamePatternMatchesAll=true&useUnicode=true&characterEncoding=UTF-8
username: root
password: [email protected]
type: com.zaxxer.hikari.HikariDataSource
initialSize: 5
minIdle: 10
maxActive: 50
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
maxEvictableIdleTimeMillis: 900000
validationQuery: SELECT 1 FROM DUAL
sharding:
master-slave-rules:
master-test0: # Which primary node
master-datasource-name: ds0 # Specify the name of the master node
slave-data-source-names: ds0,ds1 # Specify the name of the read node , Multiple read nodes are separated by commas
# Configure select policy from library , Provide polling and random , Here we choose polling
masterslave:
load-balance-algorithm-type: round_robin
props:
sql:
show: false # The log shows SQL
datasource:
# Dynamic data source configuration
dynamic:
datasource:
slave:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://172.18.11.9:3306/quarant_db?serverTimezone=Asia/Shanghai&useLegacyDatetimeCode=false&useSSL=false&nullNamePatternMatchesAll=true&useUnicode=true&characterEncoding=UTF-8
username: root
password: [email protected]
health:
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://localhost:5432/postgres?currentSchema=rcw
username: postgres
password: admin
type: com.zaxxer.hikari.HikariDataSource
hikari:
min-idle: 5
max-pool-size: 100
auto-commit: true
idle-timeout: 60000
max-lifetime: 1800000
connection-timeout: 30000
connection-test-query: SELECT 1
The default is shardingsphere Two data sources configured , If you want to switch data sources @DS Annotations can be easily switched .
@GetMapping("/querydb3")
// data source db3
@DS("db3")
public String querydb3() {
QuarantineInfo quarantineInfo = quarantineInfoService.getById(53);
return JSON.toJSONString(quarantineInfo);
}// Default data source
@GetMapping("/query")
public String query() {
QuarantineInfo quarantineInfo = quarantineInfoService.getById(53);
return JSON.toJSONString(quarantineInfo);
}
边栏推荐
- softmax的近似之NCE详解
- QT based tensorrt accelerated yolov5
- Download and install node, NPM and yarn
- [combinatorics] number of solutions of indefinite equations (number of combinations of multiple sets R | number of non negative integer solutions of indefinite equations | number of integer solutions
- 二进制流转换成字节数组
- Pytoch lightweight visualization tool wandb (local)
- QQ小程序开发之 一些前期准备:预约开发账号、下载安装开发者工具、创建qq小程序
- Gavin teacher's perception of transformer live class - rasa project's actual banking financial BOT Intelligent Business Dialogue robot architecture, process and phenomenon decryption through rasa inte
- VS 2019安装及配置opencv
- MySQL practice 45 lecture [transaction isolation]
猜你喜欢

Section 26 detailed explanation and demonstration of IPSec virtual private network configuration experiment - simulation experiment based on packettracer8.0

The idea setting code is in UTF-8 idea Properties configuration file Chinese garbled

Positioning (relative positioning, absolute positioning, fixed positioning, Z-index) 2022-2-11
![MySQL practice 45 lecture [transaction isolation]](/img/a5/5420651d6be51e892976f02be8c43c.png)
MySQL practice 45 lecture [transaction isolation]

Pytoch configuration

Limit of one question per day

简易版 微信小程序开发之页面跳转、数据绑定、获取用户信息、获取用户位置信息

MySQL MAC download and installation tutorial

Pat class B "1104 forever" DFS optimization idea

Small guide for rapid formation of manipulator (VIII): kinematic modeling (standard DH method)
随机推荐
Téléchargement et installation du client Filezilla
Basic operations of mongodb [add, delete, modify, query]
Elsevier latex submitted the article pdftex def Error: File `thumbnails/cas-email. jpeg‘ not found: using draf
Pytoch lightweight visualization tool wandb (local)
Applet get user avatar and nickname
The calculation of stripe, kernel and padding in CNN
PAT乙级常用函数用法总结
[combinatorics] number of solutions of indefinite equations (number of combinations of multiple sets R | number of non negative integer solutions of indefinite equations | number of integer solutions
MongoDB复制集【主从复制】
sigaction的使用
Gavin teacher's perception of transformer live class - rasa project's actual banking financial BOT Intelligent Business Dialogue robot architecture, process and phenomenon decryption through rasa inte
机械臂速成小指南(八):运动学建模(标准DH法)
Limit of one question per day
Stepping on pits and solutions when using inputfilter to limit EditText
Lvgl usage experience
Idea set method call ignore case
Mongodb replication set [master-slave replication]
Vs 2019 configuration tensorrt
Nce detail of softmax approximation
Vs 2019 installation and configuration opencv