当前位置:网站首页>Generate multiple databases at the same time based on multiple data sources and zero code, add, delete, modify and check restful API interfaces - mysql, PostgreSQL, Oracle, Microsoft SQL server multip
Generate multiple databases at the same time based on multiple data sources and zero code, add, delete, modify and check restful API interfaces - mysql, PostgreSQL, Oracle, Microsoft SQL server multip
2022-07-18 22:54:00 【InfoQ】
Multiple data sources
review
brief introduction
UI Interface

The core principle
Configure database connection string
#primary
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/crudapi?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=root
#postgresql
spring.datasource.hikari.data-sources[0].postgresql.driverClassName=org.postgresql.Driver
spring.datasource.hikari.data-sources[0].postgresql.url=jdbc:postgresql://localhost:5432/crudapi
spring.datasource.hikari.data-sources[0].postgresql.username=postgres
spring.datasource.hikari.data-sources[0].postgresql.password=postgres
#sqlserver
spring.datasource.hikari.data-sources[1].sqlserver.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.hikari.data-sources[1].sqlserver.url=jdbc:sqlserver://localhost:1433;SelectMethod=cursor;DatabaseName=crudapi
spring.datasource.hikari.data-sources[1].sqlserver.username=sa
spring.datasource.hikari.data-sources[1].sqlserver.password=Mssql1433
#oracle
spring.datasource.hikari.data-sources[2].oracle.url=jdbc:oracle:thin:@//localhost:1521/XEPDB1
spring.datasource.hikari.data-sources[2].oracle.driverClassName=oracle.jdbc.OracleDriver
spring.datasource.hikari.data-sources[2].oracle.username=crudapi
spring.datasource.hikari.data-sources[2].oracle.password=crudapi
#mysql
spring.datasource.hikari.data-sources[3].mysql.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.hikari.data-sources[3].mysql.url=jdbc:mysql://localhost:3306/crudapi2?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.hikari.data-sources[3].mysql.username=root
spring.datasource.hikari.data-sources[3].mysql.password=root
Dynamic data sources ——DynamicDataSource
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDataSource();
}
}
data source Context——DataSourceContextHolder
public class DataSourceContextHolder {
// Default data source primary=dataSource
private static final String DEFAULT_DATASOURCE = "dataSource";
// Save the data source connected by the thread
private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();
private static final ThreadLocal<String> HEADER_HOLDER = new ThreadLocal<>();
public static String getDataSource() {
String dataSoure = CONTEXT_HOLDER.get();
if (dataSoure != null) {
return dataSoure;
} else {
return DEFAULT_DATASOURCE;
}
}
public static void setDataSource(String key) {
if ("primary".equals(key)) {
key = DEFAULT_DATASOURCE;
}
CONTEXT_HOLDER.set(key);
}
public static void cleanDataSource() {
CONTEXT_HOLDER.remove();
}
public static void setHeaderDataSource(String key) {
HEADER_HOLDER.set(key);
}
public static String getHeaderDataSource() {
String dataSoure = HEADER_HOLDER.get();
if (dataSoure != null) {
return dataSoure;
} else {
return DEFAULT_DATASOURCE;
}
}
}
Dynamic database provider ——DynamicDataSourceProvider
@Component
@EnableConfigurationProperties(DataSourceProperties.class)
@ConfigurationProperties(prefix = "spring.datasource.hikari")
public class DynamicDataSourceProvider implements DataSourceProvider {
@Autowired
private DynamicDataSource dynamicDataSource;
private List<Map<String, DataSourceProperties>> dataSources;
private Map<Object,Object> targetDataSourcesMap;
@Resource
private DataSourceProperties dataSourceProperties;
private DataSource buildDataSource(DataSourceProperties prop) {
DataSourceBuilder<?> builder = DataSourceBuilder.create();
builder.driverClassName(prop.getDriverClassName());
builder.username(prop.getUsername());
builder.password(prop.getPassword());
builder.url(prop.getUrl());
return builder.build();
}
@Override
public List<DataSource> provide() {
Map<Object,Object> targetDataSourcesMap = new HashMap<>();
List<DataSource> res = new ArrayList<>();
if (dataSources != null) {
dataSources.forEach(map -> {
Set<String> keys = map.keySet();
keys.forEach(key -> {
DataSourceProperties properties = map.get(key);
DataSource dataSource = buildDataSource(properties);
targetDataSourcesMap.put(key, dataSource);
});
});
// to update dynamicDataSource
this.targetDataSourcesMap = targetDataSourcesMap;
dynamicDataSource.setTargetDataSources(targetDataSourcesMap);
dynamicDataSource.afterPropertiesSet();
}
return res;
}
@PostConstruct
public void init() {
provide();
}
public List<Map<String, DataSourceProperties>> getDataSources() {
return dataSources;
}
public void setDataSources(List<Map<String, DataSourceProperties>> dataSources) {
this.dataSources = dataSources;
}
public List<Map<String, String>> getDataSourceNames() {
List<Map<String, String>> dataSourceNames = new ArrayList<Map<String, String>>();
Map<String, String> dataSourceNameMap = new HashMap<String, String>();
dataSourceNameMap.put("name", "primary");
dataSourceNameMap.put("caption", " The main data source ");
dataSourceNameMap.put("database", parseDatabaseName(dataSourceProperties));
dataSourceNames.add(dataSourceNameMap);
if (dataSources != null) {
dataSources.forEach(map -> {
Set<Map.Entry<String, DataSourceProperties>> entrySet = map.entrySet();
for (Map.Entry<String, DataSourceProperties> entry : entrySet) {
Map<String, String> t = new HashMap<String, String>();
t.put("name", entry.getKey());
t.put("caption", entry.getKey());
DataSourceProperties p = entry.getValue();
t.put("database", parseDatabaseName(p));
dataSourceNames.add(t);
}
});
}
return dataSourceNames;
}
public String getDatabaseName() {
List<Map<String, String>> dataSourceNames = this.getDataSourceNames();
String dataSource = DataSourceContextHolder.getDataSource();
Optional<Map<String, String>> op = dataSourceNames.stream()
.filter(t -> t.get("name").toString().equals(dataSource))
.findFirst();
if (op.isPresent()) {
return op.get().get("database");
} else {
return dataSourceNames.stream()
.filter(t -> t.get("name").toString().equals("primary"))
.findFirst().get().get("database");
}
}
private String parseDatabaseName(DataSourceProperties p) {
String url = p.getUrl();
String databaseName = "";
if (url.toLowerCase().indexOf("databasename") >= 0) {
String[] urlArr = p.getUrl().split(";");
for (String u : urlArr) {
if (u.toLowerCase().indexOf("databasename") >= 0) {
String[] uArr = u.split("=");
databaseName = uArr[uArr.length - 1];
}
}
} else {
String[] urlArr = p.getUrl().split("\\?")[0].split("/");
databaseName = urlArr[urlArr.length - 1];
}
return databaseName;
}
public Map<Object,Object> getTargetDataSourcesMap() {
return targetDataSourcesMap;
}
}
Dynamic data source configuration ——DynamicDataSourceConfig
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class ServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class, args);
}
}
// Data source configuration class
@Configuration
@EnableConfigurationProperties(DataSourceProperties.class)
public class DynamicDataSourceConfig {
private static final Logger log = LoggerFactory.getLogger(DynamicDataSourceConfig.class);
@Resource
private DataSourceProperties dataSourceProperties;
@Bean(name = "dataSource")
public DataSource getDataSource(){
DataSourceBuilder<?> builder = DataSourceBuilder.create();
builder.driverClassName(dataSourceProperties.getDriverClassName());
builder.username(dataSourceProperties.getUsername());
builder.password(dataSourceProperties.getPassword());
builder.url(dataSourceProperties.getUrl());
return builder.build();
}
@Primary // When implementation classes of the same type exist , Select the class marked by the annotation
@Bean("dynamicDataSource")
public DynamicDataSource dynamicDataSource(){
DynamicDataSource dynamicDataSource = new DynamicDataSource();
// Default data source
dynamicDataSource.setDefaultTargetDataSource(getDataSource());
Map<Object,Object> targetDataSourcesMap = new HashMap<>();
dynamicDataSource.setTargetDataSources(targetDataSourcesMap);
return dynamicDataSource;
}
// Transaction manager DataSourceTransactionManager Construction parameters need DataSource
// Here we can see that what we give is dynamicDS This bean
@Bean
public PlatformTransactionManager transactionManager(){
return new DataSourceTransactionManager(dynamicDataSource());
}
// there JdbcTemplate Construction parameters also need a DataSource, To realize data source switching query ,
// It's also used here dynamicDS This bean
@Bean(name = "jdbcTemplate")
public JdbcTemplate getJdbc(){
return new JdbcTemplate(dynamicDataSource());
}
// there JdbcTemplate Construction parameters also need a DataSource, To realize data source switching query ,
// It's also used here dynamicDS This bean
@Bean(name = "namedParameterJdbcTemplate")
public NamedParameterJdbcTemplate getNamedJdbc(){
return new NamedParameterJdbcTemplate(dynamicDataSource());
}
}
Request header filter ——HeadFilter
@WebFilter(filterName = "headFilter", urlPatterns = "/*")
public class HeadFilter extends OncePerRequestFilter {
private static final Logger log = LoggerFactory.getLogger(HeadFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (!"/api/auth/login".equals(request.getRequestURI())
&& !"/api/auth/jwt/login".equals(request.getRequestURI())
&& !"/api/auth/logout".equals(request.getRequestURI())
&& !"/api/metadata/dataSources".equals(request.getRequestURI())) {
String dataSource = request.getParameter("dataSource");
HeadRequestWrapper headRequestWrapper = new HeadRequestWrapper(request);
if (StringUtils.isEmpty(dataSource)) {
dataSource = headRequestWrapper.getHeader("dataSource");
if (StringUtils.isEmpty(dataSource)) {
dataSource = "primary";
headRequestWrapper.addHead("dataSource", dataSource);
}
}
DataSourceContextHolder.setHeaderDataSource(dataSource);
// finish
filterChain.doFilter(headRequestWrapper, response);
} else {
filterChain.doFilter(request, response);
}
}
}
The practical application
@Aspect
public class DataSourceAspect {
private static final Logger log = LoggerFactory.getLogger(DataSourceAspect.class);
@Pointcut("within(cn.crudapi.api.controller..*)")
public void applicationPackagePointcut() {
}
@Around("applicationPackagePointcut()")
public Object dataSourceAround(ProceedingJoinPoint joinPoint) throws Throwable {
String dataSource = DataSourceContextHolder.getHeaderDataSource();
DataSourceContextHolder.setDataSource(dataSource);
try {
return joinPoint.proceed();
} finally {
DataSourceContextHolder.cleanDataSource();
}
}
}
Front end Integration
const table = {
list: function(dataSource, tableName, page, rowsPerPage, search, query, filter) {
return axiosInstance.get("/api/business/" + tableName,
{
params: {
offset: (page - 1) * rowsPerPage,
limit: rowsPerPage,
search: search,
...query,
filter: filter
},
dataSource: dataSource
}
);
},
}
axiosInstance.interceptors.request.use(
function(config) {
if (config.dataSource) {
console.log("config.dataSource = " + config.dataSource);
config.headers["dataSource"] = config.dataSource;
}
return config;
},
function(error) {
return Promise.reject(error);
}
);

Summary
crudapi brief introduction
demo demonstration
Source code address attached
GitHub Address
Gitee Address
边栏推荐
- Cache results of recursive optimization (JS)
- 10分钟自定义搭建行人分析系统,检测跟踪、行为识别、人体属性All-in-One
- leetcode--两个数组交集2
- Two stack implementation queue and two queue implementation stack (JS)
- 溢流阀力士乐ZDB10VP2-4X/315V
- openstack 相关博客
- Openstack related blog
- Tencent is all around. It's silly to ask
- Nike, the leader of sports, is "red and black" in the trend of consumption recovery
- 程序员成长第二十篇:刚晋升管理者,有哪些方面要注意?
猜你喜欢

三维点云课程(四)——聚类与模型拟合

基于多数据源零代码同时生成多个数据库CRUD增删改查RESTful API接口——MySql,PostgreSql,Oracle,Microsoft SQL Server多数据源

parker派克柱塞泵PV140R1K1T1NMMC

派克Parker比例阀D1FVE50BCVLB

sklearn线性回归完成多次项函数和正弦函数拟合

416. Partition equal sum subset · knapsack problem · dynamic programming
刘小乐教授:我与生物信息学的不解之缘

【小程序项目开发-- 京东商城】uni-app之商品列表页面 (上)

Sklearn linear regression fitting first-order term function

Deepmind's latest 114 page report "emerging barter trade behavior in Multi-Agent Reinforcement Learning"
随机推荐
北大&微软联合提出超强时间序列表示学习框架,显著提升多项时间序列任务效果
Be diligent in chatting
2022.7.14-----leetcode. seven hundred and forty-five
Error in WordPress establishing database connection
Web development from entry to proficiency I (detailed)
Cmu15445 (fall 2019) project 4 - logging & Recovery details
leetcode--两个数组交集2
(板子)AcWing841. 字符串哈希
华大110时钟校准
Marvell88Q5192 switch调试记录(BSTA1000B平台)
leetcode--49字母异位词分组
Visual studio production environment configuration scheme: slowcheetah
UCOS III learning notes (11) -- task semaphores and task message queues
(post game supplement) (great DFS) k - counting time
Two stack implementation queue and two queue implementation stack (JS)
C语言自定义类型:结构体,枚举,联合
Encapsulation and invocation of old store classes in business class library
20220714给AIO-3568J适配OpenHarmony-v3.1-beta(编译Buildroot)
416.分割等和子集·背包问题·动态规划
Web crawler technology creates its own Youdao dictionary