当前位置:网站首页>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);
}
边栏推荐
- Solve high and send system Currenttimemillis Caton
- 动态规划:最长公共子串和最长公共子序列
- 用Three.js做一個簡單的3D場景
- [mathematical logic] propositional logic (propositional and connective review | propositional formula | connective priority | truth table satisfiable contradiction tautology)
- VS 2019 配置tensorRT生成engine
- Download and install node, NPM and yarn
- 2020-01-01t00:00:00.000000z date format conversion
- Nce detail of softmax approximation
- numpy之 警告VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences
- 别再用 System.currentTimeMillis() 统计耗时了,太 Low,StopWatch 好用到爆!
猜你喜欢
随机推荐
Hi3536C V100R001C02SPC040 交叉编译器安装
VS 2019配置tensorRT
MongoDB安装 & 部署
【全民编程】《软件编程-讲课视频》【零基础入门到实战应用】
Nanning water leakage detection: warmly congratulate Guangxi Zhongshui on winning the first famous brand in Guangxi
Limit of one question per day
二进制流转换成字节数组
简易版 微信小程序开发之页面跳转、数据绑定、获取用户信息、获取用户位置信息
Pytoch lightweight visualization tool wandb (local)
VS克隆时显示403错误
基于Qt的yolov5工程
Hutool动态添加定时任务
shardingsphere动态数据源
Tidal characteristics of the Bohai Sea and the Yellow Sea
解决高並發下System.currentTimeMillis卡頓
PAT乙级“1104 天长地久”DFS优化思路
softmax的近似之NCE详解
LVGL使用心得
Stepping on pits and solutions when using inputfilter to limit EditText
Idea format code idea set shortcut key format code









