下面列出了org.springframework.boot.autoconfigure.quartz.QuartzDataSource#org.springframework.boot.jdbc.DataSourceBuilder 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Bean(name = "myBatisDataSource")
@Primary
@ConfigurationProperties(prefix = "data-source.single-db")
public DataSource userDataSource() throws IOException, SQLException {
if(!useMasterSlaveDataSource) {
logger.info("-------------------- singleDB DataSource init ---------------------");
return DataSourceBuilder.create().build();
}else {
logger.info("-------------------- masterSlave DataSource init ---------------------");
// DataSource dataSource = YamlMasterSlaveDataSourceFactory.createDataSource(new File(
// DataSourceConfiguration.class.getResource("/META-INF/yamlMasterSlave.yaml").getFile()));
// return dataSource;
return null == masterSlaveProperties.getMasterDataSourceName()
? ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingProperties.getShardingRuleConfiguration(), configMapProperties.getConfigMap(), propMapProperties.getProps())
: MasterSlaveDataSourceFactory.createDataSource(
dataSourceMap, masterSlaveProperties.getMasterSlaveRuleConfiguration(), configMapProperties.getConfigMap(), propMapProperties.getProps());
}
}
@Bean(name="dataSource")
public DataSource dataSource() throws Exception
{
//先试着用remote方式连接
String url = detectRepositoryURL();
String usr = "sa";
String pwd = "";
if ( url==null ) {
logger.error("Connect to repository database failed");
throw new Exception("Connect to repository database failed");
}
logger.info("Connect to H2 repository database in "+(url.indexOf("tcp")>0?"remote":"local")+" mode: "+url);
DataSource ds = DataSourceBuilder.create()
.driverClassName("org.h2.Driver")
.url(url)
.username(usr)
.password(pwd)
.build();
;
return ds;
}
private void runScripts(List<Resource> resources, String username, String password) {
if (resources.isEmpty()) {
return;
}
boolean continueOnError = Boolean.parseBoolean(getProperty("continue-on-error"));
ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
populator.setContinueOnError(continueOnError);
populator.setSeparator(getProperty("seperator"));
if (getProperty("sql-script-encoding") != null) {
populator.setSqlScriptEncoding(getProperty("sql-script-encoding"));
}
for (Resource resource : resources) {
populator.addScript(resource);
}
DataSource dataSource = this.dataSource;
if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
String driver = getProperty("driver-class-name");
String url = getProperty("url");
dataSource = DataSourceBuilder.create(this.getClass().getClassLoader()).driverClassName(driver).url(url)
.username(username).password(password).build();
}
DatabasePopulatorUtils.execute(populator, dataSource);
}
public DataSource toDataSource() {
DataSource dataSource;
if (url == null || url.contains("hsqldb:mem")) {
log.debug("Creating in memory HSQL database");
// Start an in-process, in-memory HSQL server
dataSource = new EmbeddedDatabaseBuilder().setType(HSQL).setName("c2mondb").build();
} else {
log.debug("Creating HSQL database at URL {}",url);
dataSource = DataSourceBuilder.create().url(url).username(username).password(password).build();
}
if (!scripts.isEmpty()) {
ResourceDatabasePopulator populator = new ResourceDatabasePopulator(scripts.toArray(new Resource[scripts.size()]));
populator.setContinueOnError(true);
DatabasePopulatorUtils.execute(populator, dataSource);
}
return dataSource;
}
/**
* create default basic data source
*
* @return DataSource
* @throws RuntimeException 异常信息
*/
@Override
public DataSource build() throws RuntimeException {
try {
DataSource dataSource = DataSourceBuilder.create().url(config.getUrl()).username(config.getUsername()).password(config.getPassword()).driverClassName(config.getDriverClassName())
// springboot 2.x default is HikariDataSource
.type(HikariDataSource.class)
.build();
return dataSource;
} catch (Exception e) {
throw new RuntimeException("Create a default data source exception", e);
}
}
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
// 配置数据源(注意,我使用的是 HikariCP 连接池),以上注解是指定数据源,否则会有冲突
return DataSourceBuilder.create().build();
}
@Bean(name = "primaryDataSource")
@Primary
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDatasource() {
return DataSourceBuilder.create().build();
}
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
// 配置数据源(注意,我使用的是 HikariCP 连接池),以上注解是指定数据源,否则会有冲突
return DataSourceBuilder.create().build();
}
@Bean(name = "baseDataSource")
@Qualifier("baseDataSource")
@ConfigurationProperties(prefix = "spring.datasource.base")
@Primary
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
/**
* create default basic data source
*
* @return {@link DataSource} instance
* @throws ApiBootException ApiBoot Exception
*/
@Override
public DataSource build() throws ApiBootException {
try {
DataSource dataSource = DataSourceBuilder.create().url(config.getUrl()).username(config.getUsername()).password(config.getPassword()).driverClassName(config.getDriverClassName())
// springboot 2.x default is HikariDataSource
.type(HikariDataSource.class)
.build();
return dataSource;
} catch (Exception e) {
throw new ApiBootException("Create a default data source exception", e);
}
}
@Bean
@Primary
@Qualifier("main")
@ConfigurationProperties("main.datasource")
public DataSource mainDs() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
/**
* 通过Spring JDBC 快速创建 DataSource
* @return
*/
@Bean(name = "masterDataSource")
@Qualifier("masterDataSource")
@ConfigurationProperties(prefix = "spring.datasource.master")
public DataSource masterDataSource() {
return DataSourceBuilder.create().build();
}
/**
* 生成数据源. @Primary 注解声明为默认数据源
*/
@Bean(name = "db1DataSource")
@ConfigurationProperties(prefix = "spring.datasource.hikari.db1")
@Primary
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
private DataSource buildDataSource(DatasourceProperties property) {
return DataSourceBuilder.create()
.driverClassName(property.getDriverClassName())
.url(property.getUrl())
.username(property.getUsername())
.password(property.getPassword())
.build();
}
/**
* Builds a map of all data sources defined in the application.yml file
*
* @return
*/
@Primary
@Bean(name = "dataSourcesMtApp")
public Map<String, DataSource> dataSourcesMtApp() {
Map<String, DataSource> result = new HashMap<>();
for (DataSourceProperties dsProperties : this.multitenancyProperties.getDataSources()) {
DataSourceBuilder factory = DataSourceBuilder.create().url(dsProperties.getUrl())
.username(dsProperties.getUsername()).password(dsProperties.getPassword())
.driverClassName(dsProperties.getDriverClassName());
result.put(dsProperties.getTenantId(), factory.build());
}
return result;
}
@Lazy
@Bean("readDataSource")
@ConfigurationProperties("spring.datasource.read")
public DataSource readDataSource() {
DataSource dataSource = DataSourceBuilder.create().build();
return dataSource;
}
@Bean
public DataSource getDataSource() {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("org.h2.Driver");
dataSourceBuilder.url("jdbc:h2:mem:test");
dataSourceBuilder.username("SA");
dataSourceBuilder.password("");
return dataSourceBuilder.build();
}
@Bean
DataSource create() {
return DataSourceBuilder.create()
.username(username)
.password(password)
.url(uri.replaceAll("postgres", "jdbc:postgresql") + "/" + databaseName)
.driverClassName("org.postgresql.Driver")
.build();
}
@SuppressWarnings("unchecked")
public Map<String, DataSource> multiDatasource() {
Map<String, DataSource> map = new HashMap<>();
try {
List<SysDbmsTabsJdbcInfo> list = sysDbmsTabsJdbcInfoDao.findAll();
Class<DataSource> type = (Class<DataSource>) Class.forName("org.apache.tomcat.jdbc.pool.DataSource");
for (SysDbmsTabsJdbcInfo sysZhcxAddr : list) {
String driverClassName = "";
String url = "";
switch (sysZhcxAddr.getType()) {
case "oracle":
driverClassName = "oracle.jdbc.driver.OracleDriver";
url = "jdbc:oracle:thin:@" + sysZhcxAddr.getIp() + ":" + sysZhcxAddr.getPort() + ":" + sysZhcxAddr.getDatabaseName();
break;
case "mysql":
// driverClassName = "com.mysql.jdbc.Driver";
driverClassName = "com.mysql.cj.jdbc.Driver";
url = "jdbc:mysql://" + sysZhcxAddr.getIp() + ":" + sysZhcxAddr.getPort() + "/" + sysZhcxAddr.getDatabaseName() + "?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull&autoReconnect=true&failOverReadOnly=false&allowPublicKeyRetrieval=true&rewriteBatchedStatements=true";
break;
default:
driverClassName = "oracle.jdbc.driver.OracleDriver";
url = "jdbc:oracle:thin:@" + sysZhcxAddr.getIp() + ":" + sysZhcxAddr.getPort() + ":" + sysZhcxAddr.getDatabaseName();
break;
}
DataSource dataSource = DataSourceBuilder.create().driverClassName(driverClassName).url(url).username(sysZhcxAddr.getUsername()).password(sysZhcxAddr.getPassword()).type(type).build();
map.put(sysZhcxAddr.getUuid(), dataSource);
}
} catch (ClassNotFoundException e) {
logger.error("程序未发现jar包 《tomcat-jdbc》 ,springboot2之后默认数据源使用 “com.zaxxer.hikari.HikariDataSource”,使用其他数据源需要单独引入包", LogsClearScheduled.class);
}
return map;
}
/**
* @throws ClassNotFoundException
* @方法名 getDataSource
* @功能 TODO(这里用一句话描述这个方法的作用)
* @参数 @param uuid
* @参数 @return
* @返回 DataSource
* @author Administrator
* @throws
*/
@SuppressWarnings("unchecked")
public DataSource getDataSource(String uuid) {
Optional<SysDbmsTabsJdbcInfo> optional = sysDbmsTabsJdbcInfoDao.findById(uuid);
if (optional.isPresent()) {
try {
SysDbmsTabsJdbcInfo sysZhcxAddr = optional.get();
Class<DataSource> type = (Class<DataSource>) Class.forName("org.apache.tomcat.jdbc.pool.DataSource");
String driverClassName = "";
String url = "";
switch (sysZhcxAddr.getType()) {
case "oracle":
driverClassName = "oracle.jdbc.driver.OracleDriver";
url = "jdbc:oracle:thin:@" + sysZhcxAddr.getIp() + ":" + sysZhcxAddr.getPort() + ":" + sysZhcxAddr.getDatabaseName();
break;
case "mysql":
// driverClassName = "com.mysql.jdbc.Driver";
driverClassName = "com.mysql.cj.jdbc.Driver";
url = "jdbc:mysql://" + sysZhcxAddr.getIp() + ":" + sysZhcxAddr.getPort() + "/" + sysZhcxAddr.getDatabaseName() + "?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull&autoReconnect=true&failOverReadOnly=false&allowPublicKeyRetrieval=true&rewriteBatchedStatements=true";
break;
default:
driverClassName = "oracle.jdbc.driver.OracleDriver";
url = "jdbc:oracle:thin:@" + sysZhcxAddr.getIp() + ":" + sysZhcxAddr.getPort() + ":" + sysZhcxAddr.getDatabaseName();
break;
}
return DataSourceBuilder.create().driverClassName(driverClassName).url(url).username(sysZhcxAddr.getUsername()).password(sysZhcxAddr.getPassword()).type(type).build();
} catch (ClassNotFoundException e) {
logger.error("程序未发现jar包 《tomcat-jdbc》 ,springboot2之后默认数据源使用 “com.zaxxer.hikari.HikariDataSource”,使用其他数据源需要单独引入包", LogsClearScheduled.class);
}
}
return null;
}
/**
* create data source for the given Syndesis Data source
* @return {@link TeiidDataSource}
*/
public TeiidDataSourceImpl createDatasource(String deploymentName, DefaultSyndesisDataSource scd) {
DataSource ds = DataSourceBuilder.create().url(scd.getProperty("url"))
.username(scd.getProperty("username") != null ? scd.getProperty("username")
: scd.getProperty("user"))
.password(scd.getProperty("password")).build();
if (ds instanceof HikariDataSource) {
((HikariDataSource)ds).setMaximumPoolSize(10);
((HikariDataSource)ds).setMinimumIdle(0);
((HikariDataSource)ds).setIdleTimeout(60000);
((HikariDataSource)ds).setScheduledExecutor(EXECUTOR);
}
Map<String, String> importProperties = new HashMap<String, String>();
Map<String, String> translatorProperties = new HashMap<String, String>();
if (scd.getProperty("schema") != null) {
importProperties.put("importer.schemaName", scd.getProperty("schema"));
importProperties.put("importer.UseFullSchemaName", "false");
} else {
//either we need to try the import and possibly fail,
//or just start off with this as true and include the
//the source schema names. for now this is simpler
importProperties.put("importer.UseFullSchemaName", "true");
}
importProperties.put("importer.TableTypes", "TABLE,VIEW");
importProperties.put("importer.UseQualifiedName", "true");
importProperties.put("importer.UseCatalogName", "false");
importProperties.put("importer.UseFullSchemaName", "false");
TeiidDataSourceImpl teiidDS = new TeiidDataSourceImpl(scd.getSyndesisConnectionId(), deploymentName, getTranslatorName(), ds);
teiidDS.setImportProperties(importProperties);
teiidDS.setTranslatorProperties(translatorProperties);
return teiidDS;
}
@Primary
@Bean(name = "writeDataSource")
@Qualifier("writeDataSource")
@ConfigurationProperties(prefix = "spring.datasource.write")
public DataSource writeDataSource(){
return DataSourceBuilder.create().build();
}
@Bean
public DataSource getDataSource() {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("org.h2.Driver");
dataSourceBuilder.url("jdbc:h2:mem:test");
dataSourceBuilder.username("SA");
dataSourceBuilder.password("");
return dataSourceBuilder.build();
}
@Override
public void onCreate(Organization organization, DataSourceInfo dataSourceInfo,
DataSourceBuilder<?> dataSourceBuilder) {
if ("com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(dataSourceInfo.getDriverClassName())) {
String url = dataSourceInfo.getUrl();
if (!url.contains(databaseNameService.getDatabaseName(Constants.MASTER))) {
String databaseName = databaseNameService.getDatabaseName(Constants.MASTER);
url += "/" + databaseName;
dataSourceBuilder.url(url);
}
}
}
@Override
public void onCreate(Organization organization, DataSourceInfo dataSourceInfo,
DataSourceBuilder<?> dataSourceBuilder) {
if ("com.mysql.jdbc.Driver".equals(dataSourceInfo.getDriverClassName())) {
String url = dataSourceInfo.getUrl();
if (!url.contains(databaseNameService.getDatabaseName(Constants.MASTER))) {
String databaseName = databaseNameService.getDatabaseName(Constants.MASTER);
url += "/" + databaseName;
dataSourceBuilder.url(url);
}
}
}
@SuppressWarnings("unchecked")
@Override
public DataSource createDataSource(Organization organization) {
return MultitenantUtils.doQuery(() -> {
DataSource dataSouce = null;
DataSourceInfo dataSourceInfo = dataSourceInfoService.get(organization);
if (StringUtils.isEmpty(dataSourceInfo.getJndiName())) {
String master = Constants.MASTER;
if (EmbeddedDatabaseConnection.isEmbedded(dataSourceInfo.getDriverClassName())) {
master = properties.determineDatabaseName();
}
DataSourceBuilder<?> factory = this.properties.initializeDataSourceBuilder();
factory.url(dataSourceInfo.getUrl().replace(databaseNameService.getDatabaseName(master), databaseNameService.getDatabaseName(organization.getId())))
.username(dataSourceInfo.getUsername())
.password(dataSourceInfo.getPassword());
if (!StringUtils.isEmpty(dataSourceInfo.getDriverClassName())) {
factory.driverClassName(dataSourceInfo.getDriverClassName());
}
if (!StringUtils.isEmpty(dataSourceInfo.getType())) {
try {
factory.type((Class<? extends DataSource>) Class.forName(dataSourceInfo.getType()));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e.getMessage());
}
}
publishEvent(organization, dataSourceInfo, factory);
dataSouce = factory.build();
} else {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
dataSouce = dataSourceLookup.getDataSource(dataSourceInfo.getJndiName());
}
dataSourceMap.put(organization.getId(), dataSouce);
this.applicationContext.publishEvent(new OrgDataSourceCreateEvent(dataSouce));
return dataSouce;
});
}
private void publishEvent(Organization organization, DataSourceInfo dataSourceInfo, DataSourceBuilder<?> dataSourceBuilder) {
if (listeners != null) {
for (DataSourceCreateListener dataSourceCreateListener : listeners) {
dataSourceCreateListener.onCreate(organization, dataSourceInfo, dataSourceBuilder);
}
}
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.type(DynamicDataSource.class);
return dataSourceBuilder.build();
}
@Bean
@Primary
public DataSource developmentDataSource() {
return DataSourceBuilder
.create()
.driverClassName(DATASOURCE_DRIVER_CLASS_NAME)
.url(DATASOURCE_URL)
.username(DATASOURCE_USERNAME)
.password(DATASOURCE_PASSWORD)
.build();
}
@Bean
@Primary
public DataSource developmentDataSource() {
return DataSourceBuilder
.create()
.driverClassName(DATASOURCE_DRIVER_CLASS_NAME)
.url(DATASOURCE_URL)
.username(DATASOURCE_USERNAME)
.password(DATASOURCE_PASSWORD)
.build();
}