下面列出了org.apache.commons.logging.impl.Jdk14Logger#org.apache.commons.dbcp2.BasicDataSource 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static Connection getConnection(BasicDataSource dataSource) {
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
//注意,替换成自己本地的 mysql 数据库地址和用户名、密码
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("root123456");
//设置连接池的一些参数
dataSource.setInitialSize(10);
dataSource.setMaxTotal(50);
dataSource.setMinIdle(2);
Connection con = null;
try {
con = dataSource.getConnection();
log.info("创建连接池:{}", con);
} catch (Exception e) {
log.error("-----------mysql get connection has exception , msg = {}", e.getMessage());
}
return con;
}
/** Tests {@link com.qihoo.qsql.org.apache.calcite.adapter.jdbc.JdbcCatalogSchema}. */
@Test public void test3() throws SQLException {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl(TempDb.INSTANCE.getUrl());
dataSource.setUsername("");
dataSource.setPassword("");
final JdbcCatalogSchema schema =
JdbcCatalogSchema.create(null, "", dataSource, "PUBLIC");
assertThat(schema.getSubSchemaNames(),
is(Sets.newHashSet("INFORMATION_SCHEMA", "PUBLIC", "SYSTEM_LOBS")));
final CalciteSchema rootSchema0 =
CalciteSchema.createRootSchema(false, false, "", schema);
final Driver driver = new Driver();
final CalciteJdbc41Factory factory = new CalciteJdbc41Factory();
final String sql = "select count(*) as c from information_schema.schemata";
try (Connection connection =
factory.newConnection(driver, factory,
"jdbc:calcite:", new Properties(), rootSchema0, null);
Statement stmt3 = connection.createStatement();
ResultSet rs = stmt3.executeQuery(sql)) {
assertThat(CalciteAssert.toString(rs), equalTo("C=3\n"));
}
}
/**
* Wrap the provided data source and initialize the connection pool if its initial size is higher than 0.
*
* @param xaDataSource data source that needs to be wrapped
* @return wrapped data source
* @throws Exception if data source copy or connection pool initialization has failed.
*/
@Override
protected DataSource wrapDataSourceInternal(XADataSource xaDataSource) throws Exception {
BasicManagedDataSource basicManagedDataSource = new BasicManagedDataSource();
// Managed data source does't have a factory. Therefore we need to create an unmanaged data source and then copy
// it's configuration to the managed one.
BasicDataSource basicDataSource = getBasicDataSource();
copyFields(basicDataSource, basicManagedDataSource);
basicManagedDataSource.setTransactionManager(this.transactionManager);
basicManagedDataSource.setXaDataSourceInstance(xaDataSource);
// Initialize the connections pool
int initialSize = Integer.valueOf(this.properties.getDbcp().getOrDefault("initialSize", "0"));
if (initialSize > 0) {
basicManagedDataSource.setInitialSize(initialSize);
basicManagedDataSource.getLogWriter(); // A trick to trigger pool initialization
}
return basicManagedDataSource;
}
@Test
@SneakyThrows(ReflectiveOperationException.class)
public void assertWithEncryptDataSource() {
assertTrue(dataSource instanceof OrchestrationShardingSphereDataSource);
Field field = OrchestrationShardingSphereDataSource.class.getDeclaredField("dataSource");
field.setAccessible(true);
ShardingSphereDataSource shardingSphereDataSource = (ShardingSphereDataSource) field.get(dataSource);
BasicDataSource embedDataSource = (BasicDataSource) shardingSphereDataSource.getDataSourceMap().values().iterator().next();
assertThat(embedDataSource.getMaxTotal(), is(100));
assertThat(embedDataSource.getUsername(), is("sa"));
AlgorithmProvidedEncryptRuleConfiguration configuration =
(AlgorithmProvidedEncryptRuleConfiguration) shardingSphereDataSource.getSchemaContexts().getDefaultSchemaContext().getSchema().getConfigurations().iterator().next();
assertThat(configuration.getEncryptors().size(), is(1));
EncryptAlgorithm encryptAlgorithm = configuration.getEncryptors().get("order_encrypt");
assertThat(encryptAlgorithm.getType(), is("AES"));
assertThat(configuration.getTables().size(), is(1));
assertThat(configuration.getTables().iterator().next().getColumns().iterator().next().getCipherColumn(), is("cipher_order_id"));
}
/**
* Get a new herd data source based on an in-memory HSQLDB database. This data source is used for loading the configuration table as an environment property
* source as well as for the JPA entity manager. It will therefore create/re-create the configuration table which is required for the former. It also
* inserts required values for both scenarios.
*
* @return the test herd data source.
*/
@Bean
public static DataSource herdDataSource()
{
// Create and return a data source that can connect directly to a JDBC URL.
BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setDriverClassName(org.h2.Driver.class.getName());
basicDataSource.setUsername("");
basicDataSource.setPassword("");
basicDataSource.setUrl("jdbc:h2:mem:herdTestDb");
// Create and populate the configuration table.
// This is needed for all data source method calls since it is used to create the environment property source which happens before
// JPA and other non-static beans are initialized.
ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
resourceDatabasePopulator.addScript(new ClassPathResource("createConfigurationTableAndData.sql"));
DatabasePopulatorUtils.execute(resourceDatabasePopulator, basicDataSource); // This is what the DataSourceInitializer does.
return basicDataSource;
}
private BasicDataSource createDataSource() {
final DbProperties dbProperties = getDbProperties();
BasicDataSource basicDataSource = new BasicDataSource();
if (isBlank(dbProperties.url())) {
return DefaultH2DataSource.defaultH2DataSource(basicDataSource, dbProperties);
}
basicDataSource.setDriverClassName(dbProperties.driver());
basicDataSource.setUrl(dbProperties.url());
basicDataSource.setUsername(dbProperties.user());
basicDataSource.setPassword(dbProperties.password());
basicDataSource.setMaxTotal(dbProperties.maxTotal());
basicDataSource.setMaxIdle(dbProperties.maxIdle());
basicDataSource.setConnectionProperties(dbProperties.connectionPropertiesAsString());
return basicDataSource;
}
private static void external_dbcp2() throws Exception {
for (ExternalDataSource ds : Config.externalDataSources()) {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(ds.getDriverClassName());
dataSource.setUrl(ds.getUrl());
dataSource.setInitialSize(0);
dataSource.setMinIdle(0);
dataSource.setMaxTotal(ds.getMaxTotal());
dataSource.setMaxIdle(ds.getMaxTotal());
dataSource.setTestOnCreate(false);
dataSource.setTestWhileIdle(false);
dataSource.setTestOnReturn(false);
dataSource.setTestOnBorrow(false);
dataSource.setUsername(ds.getUsername());
dataSource.setPassword(ds.getPassword());
String name = Config.externalDataSources().name(ds);
new Resource(Config.RESOURCE_JDBC_PREFIX + name, dataSource);
}
}
public static BasicDataSource defaultH2DataSource(BasicDataSource basicDataSource, DbProperties properties) {
File defaultDbDir = new File("db/h2db");
if (!defaultDbDir.exists()) {
defaultDbDir.mkdirs();
}
String defaultCacheSizeInMB = String.valueOf(128 * 1024); //128MB
String defaultH2Url = "jdbc:h2:./db/h2db/cruise" +
";DB_CLOSE_DELAY=-1" +
";DB_CLOSE_ON_EXIT=FALSE" + // do not close the DB on JVM exit
// ";MVCC=TRUE" +
";CACHE_SIZE=" + defaultCacheSizeInMB +
";TRACE_MAX_FILE_SIZE=16" + // http://www.h2database.com/html/features.html#trace_options
";TRACE_LEVEL_FILE=1" // http://www.h2database.com/html/features.html#trace_options
;
basicDataSource.setUrl(defaultH2Url);
basicDataSource.setUsername(StringUtils.defaultIfBlank(properties.user(), "sa"));
basicDataSource.setPassword(StringUtils.stripToEmpty(properties.password()));
return basicDataSource;
}
private static void createDatasource(String dsNameControlKey, SimpleNamingContextBuilder builder, Properties testConfig) {
String beanName = testConfig.getProperty("jdbc." + dsNameControlKey + ".beanName");
try {
String className = testConfig.getProperty("jdbc." + dsNameControlKey + ".driverClassName");
String url = testConfig.getProperty("jdbc." + dsNameControlKey + ".url");
String username = testConfig.getProperty("jdbc." + dsNameControlKey + ".username");
String password = testConfig.getProperty("jdbc." + dsNameControlKey + ".password");
Class.forName(className);
BasicDataSource ds = new BasicDataSource();
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
ds.setMaxTotal(12);
ds.setMaxIdle(4);
ds.setDriverClassName(className);
builder.bind("java:comp/env/jdbc/" + beanName, ds);
} catch (Throwable t) {
throw new RuntimeException("Error on creation datasource '" + beanName + "'", t);
}
logger.debug("created datasource {}", beanName);
}
@Test
public void spring_with_parent() throws Exception {
final MockSpan parent = mockTracer.buildSpan("parent").start();
try (Scope ignored = mockTracer.activateSpan(parent)) {
BasicDataSource dataSource = getDataSource(false);
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.execute("CREATE TABLE with_parent_1 (id INTEGER)");
jdbcTemplate.execute("CREATE TABLE with_parent_2 (id INTEGER)");
dataSource.close();
}
parent.finish();
List<MockSpan> spans = mockTracer.finishedSpans();
assertEquals(DB_CONNECTION_SPAN_COUNT + 3, spans.size());
checkSameTrace(spans);
checkNoEmptyTags(spans);
}
@Test
public void spring_with_parent_and_active_span_only() throws Exception {
final MockSpan parent = mockTracer.buildSpan("parent").start();
try (Scope ignored = mockTracer.activateSpan(parent)) {
BasicDataSource dataSource = getDataSource(true);
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.execute("CREATE TABLE with_parent_skip_1 (id INTEGER)");
jdbcTemplate.execute("CREATE TABLE with_parent_skip_2 (id INTEGER)");
dataSource.close();
}
parent.finish();
List<MockSpan> spans = mockTracer.finishedSpans();
assertEquals(DB_CONNECTION_SPAN_COUNT + 3, spans.size());
checkSameTrace(spans);
checkNoEmptyTags(spans);
}
@Test
public void spring_with_ignored_statement() throws Exception {
BasicDataSource dataSource = getDataSource(false, Arrays.asList(
"CREATE TABLE ignored (id INTEGER, TEST VARCHAR)",
"INSERT INTO ignored (id, \\\"TEST\\\") VALUES (1, 'value')"
));
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.execute("CREATE TABLE ignored (id INTEGER, TEST VARCHAR)");
jdbcTemplate.execute("INSERT INTO ignored (id, \"TEST\") VALUES (1, 'value')");
jdbcTemplate.execute("CREATE TABLE not_ignored (id INTEGER)");
dataSource.close();
List<MockSpan> finishedSpans = mockTracer.finishedSpans();
assertEquals(DB_CONNECTION_SPAN_COUNT + 1, finishedSpans.size());
checkNoEmptyTags(finishedSpans);
}
private static void createPoolIfAbsent(IDataSource dataSource) {
Assert.assertNotNull(dataSource, "Missing input datasource");
Assert.assertNotNull(dataSource.getJdbcPoolConfiguration(), "Connection pool information is not provided");
logger.debug("Creating connection pool for datasource " + dataSource.getLabel());
BasicDataSource pool = new BasicDataSource();
pool.setDriverClassName(dataSource.getDriver());
pool.setUrl(dataSource.getUrlConnection());
pool.setUsername(dataSource.getUser());
pool.setPassword(dataSource.getPwd());
pool.setMaxTotal(dataSource.getJdbcPoolConfiguration().getMaxTotal());
pool.setMaxWaitMillis(dataSource.getJdbcPoolConfiguration().getMaxWait());
pool.setRemoveAbandonedOnBorrow(dataSource.getJdbcPoolConfiguration().getRemoveAbandonedOnBorrow());
pool.setRemoveAbandonedOnMaintenance(dataSource.getJdbcPoolConfiguration().getRemoveAbandonedOnMaintenance());
pool.setRemoveAbandonedTimeout(dataSource.getJdbcPoolConfiguration().getAbandonedTimeout());
pool.setLogAbandoned(dataSource.getJdbcPoolConfiguration().getLogAbandoned());
pool.setTestOnReturn(dataSource.getJdbcPoolConfiguration().getTestOnReturn());
pool.setTestWhileIdle(dataSource.getJdbcPoolConfiguration().getTestWhileIdle());
pool.setTimeBetweenEvictionRunsMillis(dataSource.getJdbcPoolConfiguration().getTimeBetweenEvictionRuns());
pool.setMinEvictableIdleTimeMillis(dataSource.getJdbcPoolConfiguration().getMinEvictableIdleTimeMillis());
pool.setValidationQuery(dataSource.getJdbcPoolConfiguration().getValidationQuery());
dataSources.put(dataSource, pool);
}
@Test
void shouldTakeBackup(@TempDir Path tempDir) throws SQLException {
File originalDir = tempDir.resolve("originalDb").toFile();
originalDir.mkdirs();
File backupDir = tempDir.resolve("backupDir").toFile();
backupDir.mkdirs();
assertThat(backupDir.listFiles()).isNullOrEmpty();
try (BasicDataSource ds = new BasicDataSource()) {
ds.setDriverClassName(org.h2.Driver.class.getName());
ds.setUrl("jdbc:h2:" + new File(originalDir, "test").getAbsoluteFile());
ds.setUsername("sa");
ds.setPassword("");
new H2BackupProcessor().backup(backupDir, ds, null);
}
assertThat(backupDir.listFiles()).containsExactly(new File(backupDir, "db.zip"));
}
@Override
public Map<String, Integer> status(DataSource datasource) {
BasicDataSource ds = null;
try {
ds = datasource.unwrap(BasicDataSource.class);
} catch (Exception e) {
Logs.db().error(e.getLocalizedMessage(), e);
}
if (ds == null) {
Logs.db().info("ds.class({}) is not instance form BasicDataSource", datasource.getClass().getName());
return Collections.emptyMap();
}
Map<String, Integer> map = new HashMap<>();
map.put("active", ds.getNumActive());
map.put("idle", ds.getNumIdle());
map.put("minIdle", ds.getMinIdle());
map.put("maxIdle", ds.getMaxIdle());
map.put("maxTotal", ds.getMaxTotal());
return map;
}
private static ConnectionSource setupBasicDataSource(Settings settings) {
LOGGER.info("Setting up BasicDataSource for database connections.");
String driver = settings.get(TAG_DB_DRIVER, ConnectionUtils.class);
if (driver.isEmpty()) {
throw new IllegalArgumentException("Property '" + TAG_DB_DRIVER + "' must be non-empty");
}
try {
Class.forName(driver);
BasicDataSource ds = new BasicDataSource();
ds.setUrl(settings.get(TAG_DB_URL, ConnectionUtils.class));
ds.setUsername(settings.get(TAG_DB_USERNAME, ConnectionUtils.class));
ds.setPassword(settings.get(TAG_DB_PASSWRD, ConnectionUtils.class));
ds.setMaxIdle(settings.getInt(TAG_DB_MAXIDLE, ds.getMaxIdle()));
ds.setMaxTotal(settings.getInt(TAG_DB_MAXCONN, ds.getMaxTotal()));
ds.setMinIdle(settings.getInt(TAG_DB_MINIDLE, ds.getMinIdle()));
return new ConnectionSourceBasicDataSource(ds);
} catch (ClassNotFoundException exc) {
throw new IllegalArgumentException(exc);
}
}
/**
* apache commons dbcp2 数据源
*
* @return
*/
protected static DataSource getDBCP2DataSource() {
//创建BasicDataSource类对象
BasicDataSource datasource = new BasicDataSource();
//数据库连接信息(必须)
datasource.setDriverClassName("com.mysql.jdbc.Driver");
datasource.setUrl("jdbc:mysql://localhost:3306/ztree?useUnicode=true&characterEncoding=utf-8&useSSL=false");
datasource.setUsername("root");
datasource.setPassword("123456");
//连接池中的连接数量配置(可选)
datasource.setInitialSize(10);//初始化的连接数
datasource.setMaxOpenPreparedStatements(8);//最大连接数
datasource.setMaxIdle(5);//最大空闲连接
datasource.setMinIdle(1);//最小空闲连接
return datasource;
}
public AbstractMysqlHandler() throws Exception{
shardCount = Integer.parseInt(System.getProperty(PROP_SHARD_CNT));
for(int i=0; i<shardCount; i++){
final BasicDataSource ds = new BasicDataSource();
ds.setMaxTotal(1024);
ds.setMaxIdle(1024);
ds.setMinIdle(0);
ds.setUrl(System.getProperty(String.format(PROP_SHARD_URL, i)));
ds.setUsername(System.getProperty(String.format(PROP_SHARD_USERNAME, i)));
ds.setPassword(System.getProperty(String.format(PROP_SHARD_PASSWORD, i)));
dataSourceList.add(ds);
}
// final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
// scriptEngine = scriptEngineManager.getEngineByName(SCRIPT_ENGINE_NAME);
// scriptEngine.eval(System.getProperty(PROP_SCRIPT));
}
/** Tests {@link org.apache.calcite.adapter.jdbc.JdbcCatalogSchema}. */
@Test void test3() throws SQLException {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl(TempDb.INSTANCE.getUrl());
dataSource.setUsername("");
dataSource.setPassword("");
final JdbcCatalogSchema schema =
JdbcCatalogSchema.create(null, "", dataSource, "PUBLIC");
assertThat(schema.getSubSchemaNames(),
is(Sets.newHashSet("INFORMATION_SCHEMA", "PUBLIC", "SYSTEM_LOBS")));
final CalciteSchema rootSchema0 =
CalciteSchema.createRootSchema(false, false, "", schema);
final Driver driver = new Driver();
final CalciteJdbc41Factory factory = new CalciteJdbc41Factory();
final String sql = "select count(*) as c from information_schema.schemata";
try (Connection connection =
factory.newConnection(driver, factory,
"jdbc:calcite:", new Properties(), rootSchema0, null);
Statement stmt3 = connection.createStatement();
ResultSet rs = stmt3.executeQuery(sql)) {
assertThat(CalciteAssert.toString(rs), equalTo("C=3\n"));
}
}
private BasicDataSource initDatasource(ServicesControl mysql,
MySQLConfiguration configuration,
Object driverClass,
boolean runAsRoot) {
String hostname = mysql.getHost();
Object port = mysql.getPort();
String schema = configuration.getSchema();
String username = runAsRoot ? "root" : configuration.getUsername();
String password = configuration.getPassword();
Objects.requireNonNull(hostname, String.format("Configuration required: %s", BinaryLogSupplier.Configuration.MYSQL_HOSTNAME));
Objects.requireNonNull(schema, String.format("Configuration required: %s", BinaryLogSupplier.Configuration.MYSQL_SCHEMA));
Objects.requireNonNull(username, String.format("Configuration required: %s", BinaryLogSupplier.Configuration.MYSQL_USERNAME));
Objects.requireNonNull(password, String.format("Configuration required: %s", BinaryLogSupplier.Configuration.MYSQL_PASSWORD));
return this.getDataSource(driverClass.toString(),
hostname,
Integer.parseInt(port.toString()),
schema,
username,
password);
}
public DataSource createDataSource() {
final String driverClass = (String) dbConfig.get("javax.persistence.jdbc.driver");
final String connectionUrl = (String) dbConfig.get("javax.persistence.jdbc.url");
final String username = (String) dbConfig.get("javax.persistence.jdbc.user");
final String password = (String) dbConfig.get("javax.persistence.jdbc.password");
final BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(driverClass);
ds.setUsername(username);
ds.setPassword(password);
ds.setUrl(connectionUrl);
ds.setMinIdle(1);
ds.setMaxIdle(2);
return ds;
}
@Nonnull
static DataSource createDataSource(@Nonnull final String pgUrl,
@Nonnull final String userName,
@Nonnull final String password) {
PgConnectionValidators.pgUrlNotBlankAndValid(pgUrl, "pgUrl");
PgConnectionValidators.userNameNotBlank(userName);
PgConnectionValidators.passwordNotBlank(password);
final BasicDataSource dataSource = new BasicDataSource();
setCommonProperties(dataSource, userName, password);
dataSource.setUrl(pgUrl);
return dataSource;
}
private static void setCommonProperties(@Nonnull final BasicDataSource dataSource,
@Nonnull final String userName,
@Nonnull final String password) {
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUsername(userName);
dataSource.setPassword(password);
dataSource.setValidationQuery("select 1");
dataSource.setMaxTotal(1);
dataSource.setMaxIdle(1);
dataSource.setMaxOpenPreparedStatements(1);
}
/**
* open() 方法中建立连接,这样不用每次 invoke 的时候都要建立连接和释放连接
*
* @param parameters
* @throws Exception
*/
@Override
public void open(Configuration parameters) throws Exception {
super.open(parameters);
dataSource = new BasicDataSource();
connection = getConnection(dataSource);
String sql = "insert into Student(id, name, password, age) values(?, ?, ?, ?);";
if (connection != null) {
ps = this.connection.prepareStatement(sql);
}
}
@Test
public void run() throws OpenEJBException, NamingException, IOException {
final File tempWar = new File("target/AppDataSourceTest");
tempWar.mkdirs();
new File(tempWar, "WEB-INF").mkdirs();
IO.writeString(new File(tempWar, "WEB-INF/resources.xml"),
"<resources>\n" +
"<Resource id=\"java:app/gace/MyDS\" type=\"DataSource\">\n" +
"DataSourceCreator=dbcp\n" +
"</Resource>\n" +
"</resources>\n");
final Collection<LogRecord> records = new ArrayList<>();
try (final Container c = new Container(new Configuration().randomHttpPort())) {
Jdk14Logger.class.cast(LogFactory.getLog(BasicDataSource.class)).getLogger().addHandler(new Handler() {
@Override
public void publish(final LogRecord record) {
if (record.getLevel() == Level.SEVERE || record.getLevel() == Level.WARNING) {
records.add(record);
}
}
@Override
public void flush() {
// no-op
}
@Override
public void close() throws SecurityException {
// no-op
}
});
c.deploy(null, tempWar);
}
// if we have the JMX bug of dbcp2 integration (in 7.0.0) then we have a WARNING record from BasicDataSource.close()
// saying:
// Failed to unregister the JMX name:
// Tomcat:type=DataSource,host=localhost,context=/AppDataSourceTest,class=javax.sql.DataSource,name="openejb/Resource/AppDataSourceTest/app/gace/MyDS"
assertTrue(records.isEmpty());
}
@Bean(destroyMethod = "")
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl( dburl );
dataSource.setUsername( dbUser );
dataSource.setPassword( dbPass );
dataSource.setInitialSize( 2 );
dataSource.setValidationQuery( validationQuery );
return dataSource;
}
@Test
@SneakyThrows(ReflectiveOperationException.class)
public void assertDataSource() {
assertTrue(dataSource instanceof OrchestrationShardingSphereDataSource);
Field field = OrchestrationShardingSphereDataSource.class.getDeclaredField("dataSource");
field.setAccessible(true);
ShardingSphereDataSource shardingSphereDataSource = (ShardingSphereDataSource) field.get(dataSource);
for (DataSource each : shardingSphereDataSource.getDataSourceMap().values()) {
assertThat(((BasicDataSource) each).getMaxTotal(), is(16));
assertThat(((BasicDataSource) each).getUsername(), is("root"));
}
Collection<ShardingSphereRule> rules = shardingSphereDataSource.getSchemaContexts().getDefaultSchemaContext().getSchema().getRules();
assertThat(rules.size(), is(1));
assertMasterSlaveRule((MasterSlaveRule) rules.iterator().next());
}
DataSource buildDatasource() {
if (getDataSource() == null) {
BasicDataSource basicDataSource = new BasicDataSource();
if (getDriverClassName() != null) {
basicDataSource.setDriverClassName(getDriverClassName().get());
}
if (getUrl() != null) {
basicDataSource.setUrl(getUrl().get());
}
if (getUsername() != null) {
basicDataSource.setUsername(getUsername().get());
}
if (getPassword() != null) {
basicDataSource.setPassword(getPassword().get());
}
if (getConnectionProperties() != null && getConnectionProperties().get() != null) {
basicDataSource.setConnectionProperties(getConnectionProperties().get());
}
if (getConnectionInitSqls() != null
&& getConnectionInitSqls().get() != null
&& !getConnectionInitSqls().get().isEmpty()) {
basicDataSource.setConnectionInitSqls(getConnectionInitSqls().get());
}
return basicDataSource;
}
return getDataSource();
}
@Test
public void assertWithShardingSphereDataSource() {
assertThat(dataSource, instanceOf(ShardingSphereDataSource.class));
SchemaContexts schemaContexts = ((ShardingSphereDataSource) dataSource).getSchemaContexts();
for (DataSource each : ((ShardingSphereDataSource) dataSource).getDataSourceMap().values()) {
assertThat(((BasicDataSource) each).getMaxTotal(), is(100));
}
assertTrue(schemaContexts.getProps().<Boolean>getValue(ConfigurationPropertyKey.SQL_SHOW));
assertTrue(schemaContexts.getProps().getValue(ConfigurationPropertyKey.SQL_SHOW));
assertThat(schemaContexts.getProps().getValue(ConfigurationPropertyKey.EXECUTOR_SIZE), is(100));
}
/**
* 进行数据库连接
*/
public void connect() {
// 获取数据库连接池
BasicDataSource dataSource = DatabaseHelper.getDataSource();
if (url.isEmpty()) {
throw new RuntimeException("数据库url不能为空");
}
// 对 mysql 数据库进行处理
if (url.contains("jdbc:mysql")) {
// 对 url 进行处理
if (!url.contains("?")) {
// url 不包括问号时,添加SSL、编码信息、时区等信息
url += "?useSSL=true&useUnicode=true&characterEncoding=UTF-8&useOldAliasMetadataBehavior=true&autoReconnect=true&serverTimezone=UTC";
} else if (url.contains("?")) {
// url 包括问号时,添加SSL、编码信息、时区等信息
url += "&useSSL=true&useUnicode=true&characterEncoding=UTF-8&useOldAliasMetadataBehavior=true&autoReconnect=true&serverTimezone=UTC";
}
}
// 设置数据库信息
dataSource.setUrl(url);
dataSource.setUsername((username != null) ? username : "root");
dataSource.setPassword((password != null) ? password : "123456");
dataSource.setDriverClassName((driverClassName != null) ? driverClassName : "com.mysql.jdbc.Driver");
// 对 Oracle 数据库进行处理
if (url.contains("jdbc:oracle")) {
// 修改 Oracle 数据库的日期格式
DatabaseHelper.executeUpdate("alter session set nls_date_format='yyyy-MM-dd hh24:mi:ss'");
}
}