我有一个出库程序,大概功能就是通过数据库配置一条任务记录来指定出哪张表、哪些字段,多久出一次等。程序是通过启动时加入参来判断配的是哪一条任务。
现在想把它做成接口的形式来增加通用性,想让不同的系统都使用这个功能,有以下问题:
1、如何通过接口来配置数据库连接池的那些参数?
数据库连接参数你改它干啥?
你要连不同的库,可以考虑动态数据源
原始jdbc连接 + sql拼接不就行了吗
package com.example.demo8;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;
@Component
@Primary
public class DataSourceDynamic implements DataSource {
private final static ThreadLocal<DataSource> dataSourceThreadLocal = new ThreadLocal<>();
@Autowired
@Qualifier("dataSource")
private DataSource dataSource;
public static void setDataSourceThreadLocal(DataSource dataSource) {
dataSourceThreadLocal.set(dataSource);
}
private DataSource getDataSource() {
final DataSource dataSource = dataSourceThreadLocal.get();
if (dataSource == null) {
return this.dataSource;
}
return dataSource;
}
@Override
public Connection getConnection() throws SQLException {
return getDataSource().getConnection();
}
@Override
public Connection getConnection(String s, String s1) throws SQLException {
return getDataSource().getConnection(s, s1);
}
@Override
public PrintWriter getLogWriter() throws SQLException {
return getDataSource().getLogWriter();
}
@Override
public void setLogWriter(PrintWriter printWriter) throws SQLException {
getDataSource().setLogWriter(printWriter);
}
@Override
public void setLoginTimeout(int i) throws SQLException {
getDataSource().setLoginTimeout(i);
}
@Override
public int getLoginTimeout() throws SQLException {
return getDataSource().getLoginTimeout();
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return getDataSource().getParentLogger();
}
@Override
public <T> T unwrap(Class<T> aClass) throws SQLException {
return getDataSource().unwrap(aClass);
}
@Override
public boolean isWrapperFor(Class<?> aClass) throws SQLException {
return getDataSource().isWrapperFor(aClass);
}
}
package com.example.demo8;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
public class Api {
void invoke(String url, String username, String password) {
try {
DataSourceDynamic.setDataSourceThreadLocal(new SingleConnectionDataSource(url, username, password, true));
//调用你正常的业务逻辑
} finally {
DataSourceDynamic.setDataSourceThreadLocal(null);
}
}
}
你应该搜配置多动态数据源;
但是不建议配置多个动态数据源,直接写个工具用jdbc就好了,想连哪儿连哪儿,还不占资源
你这么做会感觉后续会有很多问题 如果用户数据不在同一个库会有很多坑,比如展示一个列表等不同的库都有一个用户的数据 分页查询很不好弄 我感觉你可以根据分裤分表做shardingjdbc分裤分表 (看你自己项目的业务量)
搜配置多动态数据源
把文章里那些配置内容修改为接口的入参就可以了。还有一篇是通过yml配置的,欢迎借鉴。
1,使用双数据源形式,不推荐,你每个用到得项目都要配置这种双数据源
2、使用springcloud模式,推荐,把这个模块单独部署一个springboot项目当做独立的接口维护,其他项目直接引入即可