com.zaxxer.hikari.HikariDataSource Java Examples

The following examples show how to use com.zaxxer.hikari.HikariDataSource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractEmbeddedDataSourceHelper.java    From freeacs with MIT License 8 votes vote down vote up
public static void setUpBeforeClass() throws ManagedProcessException {
    randomFolder = "./db/" + UUID.randomUUID();
    DBConfigurationBuilder configBuilder = DBConfigurationBuilder.newBuilder();
    configBuilder.setPort(3307);
    configBuilder.setDataDir(randomFolder);
    db = DB.newEmbeddedDB(configBuilder.build());
    db.start();
    db.createDB("acs", "acs", "acs");
    db.source("install.sql", "acs", "acs", "acs");
    String url = configBuilder.getURL("acs");
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setDataSourceClassName("org.mariadb.jdbc.MariaDbDataSource");
    hikariConfig.addDataSourceProperty("url", url);
    hikariConfig.addDataSourceProperty("user", "acs");
    hikariConfig.addDataSourceProperty("password", "acs");
    dataSource = new HikariDataSource(hikariConfig);
}
 
Example #2
Source File: HikariPool.java    From Java-11-Cookbook-Second-Edition with MIT License 7 votes vote down vote up
private static DataSource createDataSource3() {
    Properties props = new Properties();
    props.setProperty("poolName", "cookpool");
    props.setProperty("driverClassName", "org.postgresql.Driver");
    props.setProperty("jdbcUrl", "jdbc:postgresql://localhost/cookbook");
    props.setProperty("username", "cook");
    //props.setProperty("password", "123Secret");
    props.setProperty("maximumPoolSize", "10");
    props.setProperty("minimumIdle", "2");
    props.setProperty("dataSource.cachePrepStmts","true");
    props.setProperty("dataSource.prepStmtCacheSize", "256");
    props.setProperty("dataSource.prepStmtCacheSqlLimit", "2048");
    props.setProperty("dataSource.useServerPrepStmts","true");

    HikariConfig config = new HikariConfig(props);
    HikariDataSource ds = new HikariDataSource(config);
    return ds;
}
 
Example #3
Source File: TestDataConfig.java    From Spring with Apache License 2.0 7 votes vote down vote up
@Bean
public DataSource dataSource() {
    try {
        final HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setDriverClassName(driverClassName);
        hikariConfig.setJdbcUrl(url);
        hikariConfig.setUsername(username);
        hikariConfig.setPassword(password);

        hikariConfig.setMaximumPoolSize(5);
        hikariConfig.setConnectionTestQuery("SELECT 1");
        hikariConfig.setPoolName("springHikariCP");

        hikariConfig.addDataSourceProperty("dataSource.cachePrepStmts", "true");
        hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSize", "250");
        hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSqlLimit", "2048");
        hikariConfig.addDataSourceProperty("dataSource.useServerPrepStmts", "true");

        return new HikariDataSource(hikariConfig);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #4
Source File: MyBatisDataStore.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void doStart(final String storeName, final Map<String, String> attributes) throws Exception {
  boolean isContentStore = !CONFIG_DATASTORE_NAME.equalsIgnoreCase(storeName);

  dataSource = new HikariDataSource(configureHikari(storeName, attributes));
  Environment environment = new Environment(storeName, new JdbcTransactionFactory(), dataSource);
  sessionFactory = new DefaultSqlSessionFactory(configureMyBatis(environment));

  registerCommonTypeHandlers(isContentStore);

  if (beanLocator != null) {
    // register the appropriate type handlers with the store
    beanLocator.watch(TYPE_HANDLER_KEY,
        isContentStore ? CONTENT_TYPE_HANDLER_MEDIATOR : CONFIG_TYPE_HANDLER_MEDIATOR, this);
  }
}
 
Example #5
Source File: DataSourceConfigurationTest.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@Test
public void assertCreateDataSource() {
    Map<String, Object> props = new HashMap<>();
    props.put("driverClassName", "org.h2.Driver");
    props.put("jdbcUrl", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL");
    props.put("username", "root");
    props.put("password", "root");
    props.put("loginTimeout", "5000");
    props.put("test", "test");
    DataSourceConfiguration dataSourceConfig = new DataSourceConfiguration(HikariDataSource.class.getName());
    dataSourceConfig.getProps().putAll(props);
    HikariDataSource actual = (HikariDataSource) dataSourceConfig.createDataSource();
    assertThat(actual.getDriverClassName(), is("org.h2.Driver"));
    assertThat(actual.getJdbcUrl(), is("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL"));
    assertThat(actual.getUsername(), is("root"));
    assertThat(actual.getPassword(), is("root"));
}
 
Example #6
Source File: ConnectionManagerTest.java    From pxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testPoolExpirationWithActiveConnections() throws SQLException {
    MockTicker ticker = new MockTicker();
    ConnectionManager.DataSourceFactory mockFactory = mock(ConnectionManager.DataSourceFactory.class);
    HikariDataSource mockDataSource = mock(HikariDataSource.class);
    when(mockFactory.createDataSource(anyObject())).thenReturn(mockDataSource);
    when(mockDataSource.getConnection()).thenReturn(mockConnection);

    HikariPoolMXBean mockMBean = mock(HikariPoolMXBean.class);
    when(mockDataSource.getHikariPoolMXBean()).thenReturn(mockMBean);
    when(mockMBean.getActiveConnections()).thenReturn(2, 1, 0);
    manager = new ConnectionManager(mockFactory, ticker, TimeUnit.MILLISECONDS.toNanos(50));

    manager.getConnection("test-server", "test-url", connProps, true, poolProps, null);

    ticker.advanceTime(ConnectionManager.POOL_EXPIRATION_TIMEOUT_HOURS + 1, TimeUnit.HOURS);
    manager.cleanCache();

    // wait for at least 3 iteration of sleeping
    Uninterruptibles.sleepUninterruptibly(2500, TimeUnit.MILLISECONDS);

    verify(mockMBean, times(3)).getActiveConnections();
    verify(mockDataSource, times(1)).close(); // verify datasource is closed when evicted
}
 
Example #7
Source File: ConnectionPool.java    From StubbornJava with MIT License 6 votes vote down vote up
public static HikariDataSource getDataSourceFromConfig(
    Config conf
    , MetricRegistry metricRegistry
    , HealthCheckRegistry healthCheckRegistry) {

    HikariConfig jdbcConfig = new HikariConfig();
    jdbcConfig.setPoolName(conf.getString("poolName"));
    jdbcConfig.setMaximumPoolSize(conf.getInt("maximumPoolSize"));
    jdbcConfig.setMinimumIdle(conf.getInt("minimumIdle"));
    jdbcConfig.setJdbcUrl(conf.getString("jdbcUrl"));
    jdbcConfig.setUsername(conf.getString("username"));
    jdbcConfig.setPassword(conf.getString("password"));

    jdbcConfig.addDataSourceProperty("cachePrepStmts", conf.getBoolean("cachePrepStmts"));
    jdbcConfig.addDataSourceProperty("prepStmtCacheSize", conf.getInt("prepStmtCacheSize"));
    jdbcConfig.addDataSourceProperty("prepStmtCacheSqlLimit", conf.getInt("prepStmtCacheSqlLimit"));
    jdbcConfig.addDataSourceProperty("useServerPrepStmts", conf.getBoolean("useServerPrepStmts"));

    // Add HealthCheck
    jdbcConfig.setHealthCheckRegistry(healthCheckRegistry);

    // Add Metrics
    jdbcConfig.setMetricRegistry(metricRegistry);
    return new HikariDataSource(jdbcConfig);
}
 
Example #8
Source File: ConnectionManagerTest.java    From pxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testPoolExpirationNoActiveConnections() throws SQLException {
    MockTicker ticker = new MockTicker();
    ConnectionManager.DataSourceFactory mockFactory = mock(ConnectionManager.DataSourceFactory.class);
    HikariDataSource mockDataSource = mock(HikariDataSource.class);
    when(mockFactory.createDataSource(anyObject())).thenReturn(mockDataSource);
    when(mockDataSource.getConnection()).thenReturn(mockConnection);

    HikariPoolMXBean mockMBean = mock(HikariPoolMXBean.class);
    when(mockDataSource.getHikariPoolMXBean()).thenReturn(mockMBean);
    when(mockMBean.getActiveConnections()).thenReturn(0);
    manager = new ConnectionManager(mockFactory, ticker, ConnectionManager.CLEANUP_SLEEP_INTERVAL_NANOS);

    manager.getConnection("test-server", "test-url", connProps, true, poolProps, null);

    ticker.advanceTime(ConnectionManager.POOL_EXPIRATION_TIMEOUT_HOURS + 1, TimeUnit.HOURS);
    manager.cleanCache();

    Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);

    verify(mockMBean, times(1)).getActiveConnections();
    verify(mockDataSource, times(1)).close(); // verify datasource is closed when evicted
}
 
Example #9
Source File: DataSourceConfig.java    From tutorial with MIT License 6 votes vote down vote up
private DataSource createDataSource(String className, String serverName, int port, String dbName,
                                    String user, String password) {
    logger.trace("createDataSource({}, {}, {}, {}, {}, {})", className, serverName, port, dbName, user, password);
    Properties props = new Properties();
    props.setProperty("dataSourceClassName", className);
    props.setProperty("dataSource.serverName", serverName);
    if(port > 0) {
        props.setProperty("dataSource.portNumber", String.valueOf(port));
    }
    props.setProperty("dataSource.databaseName", dbName);
    if(user != null) {
        props.setProperty("dataSource.user", user);
    }
    if(password != null) {
        props.setProperty("dataSource.password", password);
    }
    props.put("dataSource.logWriter", new PrintWriter(System.out));

    HikariConfig config = new HikariConfig(props);
    config.setMaximumPoolSize(15);  //连接池最多15个连接

    HikariDataSource ds = new HikariDataSource(config);

    return ds;
}
 
Example #10
Source File: PostgresqlServerClientConnectionManager.java    From digdag with Apache License 2.0 6 votes vote down vote up
private HikariDataSource createDataSourceWithConnectionPool()
{
    DatabaseConfig databaseConfig = DatabaseConfig.convertFrom(systemConfig, "param_server");
    String url = DatabaseConfig.buildJdbcUrl(databaseConfig);

    HikariConfig hikari = new HikariConfig();
    hikari.setJdbcUrl(url);
    hikari.setDriverClassName(DatabaseMigrator.getDriverClassName(databaseConfig.getType()));
    hikari.setDataSourceProperties(DatabaseConfig.buildJdbcProperties(databaseConfig));

    hikari.setConnectionTimeout(databaseConfig.getConnectionTimeout() * 1000);
    hikari.setIdleTimeout(databaseConfig.getIdleTimeout() * 1000);
    hikari.setValidationTimeout(databaseConfig.getValidationTimeout() * 1000);
    hikari.setMaximumPoolSize(databaseConfig.getMaximumPoolSize());
    hikari.setMinimumIdle(databaseConfig.getMinimumPoolSize());

    // Here should not set connectionTestQuery (that overrides isValid) because
    // ThreadLocalTransactionManager.commit assumes that Connection.isValid returns
    // false when an error happened during a transaction.

    logger.debug("Using postgresql URL {}", hikari.getJdbcUrl());

    return new HikariDataSource(hikari);
}
 
Example #11
Source File: DataSourceConfig.java    From freeacs with MIT License 6 votes vote down vote up
@Bean
public DataSource getDataSource(Environment config) {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setDriverClassName(config.getProperty("main.datasource.driverClassName"));
    hikariConfig.setJdbcUrl(config.getProperty("main.datasource.jdbcUrl"));
    hikariConfig.setUsername(config.getProperty("main.datasource.username"));
    hikariConfig.setPassword(config.getProperty("main.datasource.password"));

    hikariConfig.setMinimumIdle(config.getProperty("main.datasource.minimum-idle", Integer.class, 1));
    hikariConfig.setMaximumPoolSize(config.getProperty("main.datasource.maximum-pool-size", Integer.class, 10));
    hikariConfig.setConnectionTestQuery("SELECT 1");
    hikariConfig.setPoolName(config.getProperty("main.datasource.poolName"));

    hikariConfig.addDataSourceProperty("dataSource.cachePrepStmts", "true");
    hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSize", "250");
    hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSqlLimit", "2048");
    hikariConfig.addDataSourceProperty("dataSource.useServerPrepStmts", "true");

    hikariConfig.setAutoCommit(true);

    return new HikariDataSource(hikariConfig);
}
 
Example #12
Source File: DatabaseConfig.java    From spring-security-jwt-rest-stateless with MIT License 6 votes vote down vote up
@Bean(name = "sessionFactory")
public LocalSessionFactoryBean hibernate5SessionFactoryBean(){
    LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
    localSessionFactoryBean.setDataSource(appContext.getBean(HikariDataSource.class));
    localSessionFactoryBean.setAnnotatedClasses(
            AppUser.class
    );

    Properties properties = new Properties();
    properties.put("hibernate.dialect","org.hibernate.dialect.MySQLDialect");
    //properties.put("hibernate.current_session_context_class","thread");
    properties.put("hibernate.hbm2ddl.auto","update");

    localSessionFactoryBean.setHibernateProperties(properties);
    return localSessionFactoryBean;
}
 
Example #13
Source File: DefaultJdbcComponent.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a datasource from the given jdbc config info.
 */
@SuppressWarnings("nls")
protected DataSource datasourceFromConfig(JdbcOptionsBean config) {
    Properties props = new Properties();
    props.putAll(config.getDsProperties());
    setConfigProperty(props, "jdbcUrl", config.getJdbcUrl());
    setConfigProperty(props, "username", config.getUsername());
    setConfigProperty(props, "password", config.getPassword());

    setConfigProperty(props, "connectionTimeout", config.getConnectionTimeout());
    setConfigProperty(props, "idleTimeout", config.getIdleTimeout());
    setConfigProperty(props, "maxPoolSize", config.getMaximumPoolSize());
    setConfigProperty(props, "maxLifetime", config.getMaxLifetime());
    setConfigProperty(props, "minIdle", config.getMinimumIdle());
    setConfigProperty(props, "poolName", config.getPoolName());
    setConfigProperty(props, "autoCommit", config.isAutoCommit());

    HikariConfig hikariConfig = new HikariConfig(props);
    return new HikariDataSource(hikariConfig);
}
 
Example #14
Source File: HikariCPPlugin.java    From jfinal-api-scaffold with MIT License 6 votes vote down vote up
@Override
    public boolean start() {
        HikariConfig config = new HikariConfig();
        config.setMaximumPoolSize(maxPoolSize);
//        config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
        config.setDriverClassName(driverClass);
        config.setJdbcUrl(jdbcUrl);
        config.setUsername(user);
        config.setPassword(password);
        
        //防止中文乱码
        config.addDataSourceProperty("useUnicode", "true");
        config.addDataSourceProperty("characterEncoding", "utf8");
        
        config.setConnectionTestQuery("SELECT 1");

        this.dataSource = new HikariDataSource(config);
        
        return true;
    }
 
Example #15
Source File: DatabaseConfig.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Bean
public DataSource dataSource() throws SQLException {
    DatabaseUtil.createSchemaIfNeeded("postgresql", databaseAddress, dbName, dbUser, dbPassword, dbSchemaName);
    HikariConfig config = new HikariConfig();
    if (ssl && Files.exists(Paths.get(certFile))) {
        config.addDataSourceProperty("ssl", "true");
        config.addDataSourceProperty("sslfactory", "org.postgresql.ssl.SingleCertValidatingFactory");
        config.addDataSourceProperty("sslfactoryarg", "file://" + certFile);
    }
    if (nodeConfig.isNodeIdSpecified()) {
        config.addDataSourceProperty("ApplicationName", nodeConfig.getId());
    }
    config.setDriverClassName("io.opentracing.contrib.jdbc.TracingDriver");
    config.setJdbcUrl(String.format("jdbc:tracing:postgresql://%s/%s?currentSchema=%s", databaseAddress, dbName, dbSchemaName));
    config.setUsername(dbUser);
    config.setPassword(dbPassword);
    config.setMaximumPoolSize(poolSize);
    config.setMinimumIdle(minimumIdle);
    config.setConnectionTimeout(SECONDS.toMillis(connectionTimeout));
    config.setIdleTimeout(MINUTES.toMillis(idleTimeout));
    return new HikariDataSource(config);
}
 
Example #16
Source File: FlexyPoolTestConfiguration.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
@Override
public DataSource actualDataSource() {
    final HikariDataSource dataSource = (HikariDataSource) super.actualDataSource();

    com.vladmihalcea.flexypool.config.Configuration<HikariDataSource> configuration =
        new com.vladmihalcea.flexypool.config.Configuration.Builder<>(
            "flexy-pool-test",
            dataSource,
            HikariCPPoolAdapter.FACTORY
        )
    .build();

    return new FlexyPoolDataSource<>(
        configuration
    );
}
 
Example #17
Source File: HelperSql.java    From helper with MIT License 6 votes vote down vote up
public HelperSql(@Nonnull DatabaseCredentials credentials) {
    final HikariConfig hikari = new HikariConfig();

    hikari.setPoolName("helper-sql-" + POOL_COUNTER.getAndIncrement());

    hikari.setDataSourceClassName(DATA_SOURCE_CLASS);
    hikari.addDataSourceProperty("serverName", credentials.getAddress());
    hikari.addDataSourceProperty("port", credentials.getPort());
    hikari.addDataSourceProperty("databaseName", credentials.getDatabase());

    hikari.setUsername(credentials.getUsername());
    hikari.setPassword(credentials.getPassword());

    hikari.setMaximumPoolSize(MAXIMUM_POOL_SIZE);
    hikari.setMinimumIdle(MINIMUM_IDLE);

    hikari.setMaxLifetime(MAX_LIFETIME);
    hikari.setConnectionTimeout(CONNECTION_TIMEOUT);
    hikari.setLeakDetectionThreshold(LEAK_DETECTION_THRESHOLD);

    // ensure we use unicode (this calls #setProperties, a hack for the mariadb driver)
    hikari.addDataSourceProperty("properties", "useUnicode=true;characterEncoding=utf8");

    this.source = new HikariDataSource(hikari);
    this.stream = SqlStream.connect(this.source);
}
 
Example #18
Source File: HikariCpPooledDataSourceCreator.java    From spring-cloud-connectors with Apache License 2.0 5 votes vote down vote up
@Override
public DataSource create(RelationalServiceInfo serviceInfo, ServiceConnectorConfig serviceConnectorConfig,
						 String driverClassName, String validationQuery) {
	if (hasClass(HIKARI_DATASOURCE)) {
		logger.info("Found HikariCP on the classpath. Using it for DataSource connection pooling.");
		HikariDataSource ds = new HikariDataSource();
		setBasicDataSourceProperties(ds, serviceInfo, serviceConnectorConfig, driverClassName, validationQuery);
		return new UrlDecodingDataSource(ds, "jdbcUrl");
	} else {
		return null;
	}
}
 
Example #19
Source File: ConnectionPoolContextListener.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void contextDestroyed(ServletContextEvent event) {
  // This function is called when the Servlet is destroyed.
  HikariDataSource pool = (HikariDataSource) event.getServletContext().getAttribute("my-pool");
  if (pool != null) {
    pool.close();
  }
}
 
Example #20
Source File: SampleDatasourceProxyApplicationTests.java    From spring-boot-data-source-decorator with Apache License 2.0 5 votes vote down vote up
@Test
void contextLoads() {
    assertThat(dataSource).isInstanceOf(DecoratedDataSource.class);
    assertThat(dataSource).isInstanceOf(HikariDataSource.class);

    DecoratedDataSource decoratedDataSource = (DecoratedDataSource) dataSource;

    assertThat(decoratedDataSource.getDecoratingChain().get(0).getDataSourceDecorator()).isInstanceOf(ProxyDataSourceDecorator.class);
}
 
Example #21
Source File: DatabaseManager.java    From BedWars with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void initialize() {
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl("jdbc:mysql://" + this.host + ":" + this.port + "/" + this.database
            + "?autoReconnect=true&serverTimezone=" + TimeZone.getDefault().getID());
    config.setUsername(this.user);
    config.setPassword(this.password);
    config.addDataSourceProperty("cachePrepStmts", "true");
    config.addDataSourceProperty("prepStmtCacheSize", "250");
    config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");

    this.dataSource = new HikariDataSource(config);
}
 
Example #22
Source File: HikariCpJDK7IT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void defaultTest1() throws InterruptedException, SQLException, NoSuchMethodException {
    final HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(DATA_SOURCE_CLASS_NAME);
    config.addDataSourceProperty("url", JDBC_URL);

    HikariDataSource dataSource = new HikariDataSource(config);
    try {
        Connection connection = dataSource.getConnection();
        Assert.assertNotNull(connection);

        Thread.sleep(500);

        connection.close();

        Thread.sleep(500);

        Constructor<HikariDataSource> constructor = HikariDataSource.class.getConstructor(HikariConfig.class);

        PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
        verifier.printCache();

        verifier.verifyTrace(event(serviceType, "com.zaxxer.hikari.HikariDataSource.HikariDataSource(com.zaxxer.hikari.HikariConfig)"));
        verifier.verifyTrace(event(serviceType, "com.zaxxer.hikari.pool.BaseHikariPool.BaseHikariPool(com.zaxxer.hikari.HikariConfig, java.lang.String, java.lang.String)"));
        verifier.verifyTrace(event(serviceType, getConnectionMethod1));
        verifier.verifyTrace(event(serviceType, proxyConnectionMethod));
    } finally {
        if (dataSource != null) {
            dataSource.close();
        }
    }
}
 
Example #23
Source File: SpringLiquibaseUtilTest.java    From jhipster with Apache License 2.0 5 votes vote down vote up
@Test
public void createSpringLiquibaseFromLiquibaseDataSource() {
    DataSource liquibaseDatasource = DataSourceBuilder.create().url("jdbc:h2:mem:liquibase").username("sa").build();
    LiquibaseProperties liquibaseProperties = null;
    DataSource normalDataSource = null;
    DataSourceProperties dataSourceProperties = null;

    SpringLiquibase liquibase = SpringLiquibaseUtil.createSpringLiquibase(liquibaseDatasource, liquibaseProperties, normalDataSource, dataSourceProperties);
    assertThat(liquibase).isNotInstanceOf(DataSourceClosingSpringLiquibase.class)
        .extracting(SpringLiquibase::getDataSource).isEqualTo(liquibaseDatasource)
        .asInstanceOf(type(HikariDataSource.class))
        .hasFieldOrPropertyWithValue("jdbcUrl", "jdbc:h2:mem:liquibase")
        .hasFieldOrPropertyWithValue("username", "sa")
        .hasFieldOrPropertyWithValue("password", null);
}
 
Example #24
Source File: DataSourceManager.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
/**
 * Close, close cached data source.
 */
@Override
public void close() {
    for (HikariDataSource each : cachedDataSources.values()) {
        if (!each.isClosed()) {
            each.close();
        }
    }
    cachedDataSources.clear();
    sourceDatasources.clear();
}
 
Example #25
Source File: TestGenericRecordWriter.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws SQLException {
  // Create a table in H2 and put some data in it for querying.
  HikariConfig config = new HikariConfig();
  config.setJdbcUrl(connectionString);
  config.setUsername(username);
  config.setPassword(password);
  config.setMaximumPoolSize(2);
  dataSource = new HikariDataSource(config);

  connection = dataSource.getConnection();
  try (Statement statement = connection.createStatement()) {
    // Setup table
    statement.addBatch("CREATE SCHEMA IF NOT EXISTS TEST;");
    statement.addBatch(
        "CREATE TABLE IF NOT EXISTS TEST.TEST_TABLE " +
            "(P_ID INT NOT NULL, MSG VARCHAR(255), PRIMARY KEY(P_ID));"
    );
    statement.addBatch(
        "CREATE TABLE IF NOT EXISTS TEST.COMPOSITE_KEY " +
            "(P_ID INT NOT NULL, P_IDB INT NOT NULL, MSG VARCHAR(255), PRIMARY KEY(P_ID, P_IDB));"
    );
    String unprivUser = "unpriv_user";
    String unprivPassword = "unpriv_pass";
    statement.addBatch("CREATE USER IF NOT EXISTS " + unprivUser + " PASSWORD '" + unprivPassword + "';");
    statement.addBatch("GRANT SELECT ON TEST.TEST_TABLE TO " + unprivUser + ";");

    statement.executeBatch();
  }
}
 
Example #26
Source File: SqlConnectionPool.java    From luna with MIT License 5 votes vote down vote up
/**
 * Creates a new connection pool.
 *
 * @return The new pool.
 * @throws SQLException If the pool cannot be created.
 */
public SqlConnectionPool build() throws SQLException {
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl("jdbc:mysql://" + HOST + ":" + PORT + "/" + database + "");
    config.setUsername(USERNAME);
    config.setPassword(PASSWORD);
    config.setPoolName(poolName);
    return new SqlConnectionPool(new HikariDataSource(config));
}
 
Example #27
Source File: OracleJDBCDriverTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
private void performSimpleTest(String jdbcUrl) throws SQLException {
    HikariDataSource dataSource = getDataSource(jdbcUrl, 1);
    new QueryRunner(dataSource).query("SELECT 1 FROM dual", new ResultSetHandler<Object>() {
        @Override
        public Object handle(ResultSet rs) throws SQLException {
            rs.next();
            int resultSetInt = rs.getInt(1);
            assertEquals("A basic SELECT query succeeds", 1, resultSetInt);
            return true;
        }
    });
    dataSource.close();
}
 
Example #28
Source File: ConnectionManager.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public ConnectionManager(DatabaseVendor vendor, HikariDataSource hikariDataSource) {
  this.vendor = vendor;
  this.hikariDataSource = hikariDataSource;
  this.connectionsToCloseDuringDestroy = new HashSet<>();
  this.threadLocalConnection = new ThreadLocal<>();
  this.jdbcUtil = UtilsProvider.getJdbcUtil();
}
 
Example #29
Source File: FlexyPoolConfigurationTests.java    From spring-boot-data-source-decorator with Apache License 2.0 5 votes vote down vote up
@Test
void testSettingMicrometerMetricsFactoryByDefault() {
    contextRunner.run(context -> {
        DataSource dataSource = context.getBean(DataSource.class);
        FlexyPoolDataSource<HikariDataSource> flexyPoolDataSource = assertDataSourceOfType(dataSource, HikariDataSource.class);
        assertThat(flexyPoolDataSource).extracting("metrics").isInstanceOf(MicrometerMetrics.class);
    });
}
 
Example #30
Source File: HikariDataSourceConfiguration.java    From sofa-tracer with Apache License 2.0 5 votes vote down vote up
@Bean
public DataSource hikariDataSource() {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setJdbcUrl(jdbcUrl);
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    return dataSource;
}