当前位置:网站首页>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);
}
边栏推荐
- ffmpeg之 一张/多张图片合成视频
- Vs Code configure virtual environment
- docker安装及启动mysql服务
- Hi3536c v100r001c02spc040 cross compiler installation
- softmax的近似之NCE详解
- labelimg生成的xml文件转换为voc格式
- Mongodb installation & Deployment
- 【DRM】DRM bridge驱动调用流程简单分析
- Applet get user avatar and nickname
- Stop using system Currenttimemillis() takes too long to count. It's too low. Stopwatch is easy to use!
猜你喜欢

Lvgl usage experience

FileZilla Client下載安裝

MySQL MAC download and installation tutorial

Table structure of Navicat export database

用Three.js做一个简单的3D场景

900W+ 数据,从 17s 到 300ms,如何操作

MongoDB安装 & 部署

Vs 2019 configure tensorrt to generate engine

MongoDB簡介
![[MySQL] the difference between left join, right join and join](/img/d4/8684cd59cd1bd77e70bd4d7c7074c3.jpg)
[MySQL] the difference between left join, right join and join
随机推荐
[combinatorics] brief introduction to generating function (definition of generating function | Newton binomial coefficient | commonly used generating function | correlation with constant | correlation
[AI practice] Application xgboost Xgbregressor builds air quality prediction model (I)
Using jasmine to monitor constructors - spying on a constructor using Jasmine
ffmpeg录制屏幕和截屏
Ansible简介【暂未完成(半成品)】
[mathematical logic] predicate logic (individual word | individual domain | predicate | full name quantifier | existence quantifier | predicate formula | exercise)
Hi3536C V100R001C02SPC040 交叉编译器安装
Stepping on pits and solutions when using inputfilter to limit EditText
com.fasterxml.jackson.databind.exc.InvalidFormatException问题
[mathematical logic] propositions and connectives (propositions | propositional symbolization | truth connectives | no | conjunction | disjunction | non truth connectives | implication | equivalence)
Tidal characteristics of the Bohai Sea and the Yellow Sea
The calculation of stripe, kernel and padding in CNN
Stop using system Currenttimemillis() takes too long to count. It's too low. Stopwatch is easy to use!
Pat class B common function Usage Summary
docker安装及启动mysql服务
Hi3536c v100r001c02spc040 cross compiler installation
[leetcode question brushing day 34] 540 Unique element in array, 384 Disrupt array, 202 Happy number, 149 Maximum number of points on a line
C语言HashTable/HashSet库汇总
Lvgl usage experience
渤、黄海的潮汐特征