Java Code Examples for com.zaxxer.hikari.HikariConfig#addDataSourceProperty()

The following examples show how to use com.zaxxer.hikari.HikariConfig#addDataSourceProperty() . 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: JDBCZuulFilterDaoBuilder.java    From s2g-zuul with MIT License 6 votes vote down vote up
public JDBCZuulFilterDaoBuilder() {
	HikariConfig config = new HikariConfig();
	config.setDataSourceClassName(dataSourceClass.get());
	config.addDataSourceProperty("url", url.get());
	config.addDataSourceProperty("user", user.get());
	config.addDataSourceProperty("password", password.get());

	config.setMinimumPoolSize(minPoolSize.get());
	config.setMaximumPoolSize(maxPoolSize.get());
	config.setConnectionTimeout(connectionTimeout.get());
	config.setIdleTimeout(idleTimeout.get());
	config.setMaxLifetime(maxLifetime.get());

	this.dataSource = new HikariDataSource(config);
	this.filterTable = filterTableName.get(); //+ "_" + environment.get();
}
 
Example 2
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 3
Source File: JooqJobActivityConnectorComponent.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Bean
public JooqContext getJooqProducerContext(JooqConfiguration jooqConfiguration, EmbeddedPostgresService embeddedPostgresService) {
    HikariConfig hikariConfig = new HikariConfig();

    hikariConfig.setAutoCommit(true);

    // Connection management
    hikariConfig.setConnectionTimeout(10000);
    hikariConfig.setMaximumPoolSize(10);
    hikariConfig.setLeakDetectionThreshold(3000);

    if (jooqConfiguration.isInMemoryDb()) {
        hikariConfig.setDataSource(embeddedPostgresService.getDataSource());
    } else {
        hikariConfig.addDataSourceProperty(PGProperty.SSL.getName(), "true");
        hikariConfig.addDataSourceProperty(PGProperty.SSL_MODE.getName(), "verify-ca");
        hikariConfig.addDataSourceProperty(PGProperty.SSL_FACTORY.getName(), RDSSSLSocketFactory.class.getName());
        hikariConfig.setJdbcUrl(jooqConfiguration.getProducerDatatabaseUrl());
    }

    return new JooqContext(jooqConfiguration, new HikariDataSource(hikariConfig), embeddedPostgresService);
}
 
Example 4
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 5
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 6
Source File: MySqlIntegrationTest.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@Before
public void initializeConnectionAndTable() throws SQLException {
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource");
    config.setConnectionTestQuery("VALUES 1");
    // Note "ignorecase=true": H2 does not support `COLLATE NOCASE` for case-insensitive equals queries.
    // MySQL is by default case-insensitive so this is OK to make as an assumption.
    config.addDataSourceProperty("URL", "jdbc:h2:mem:test;ignorecase=true");
    config.addDataSourceProperty("user", "sa");
    config.addDataSourceProperty("password", "sa");
    HikariDataSource ds = new HikariDataSource(config);
    Connection connection = ds.getConnection();

    try (Statement st = connection.createStatement()) {
        st.execute("DROP TABLE IF EXISTS authme");
        st.execute(sqlInitialize);
    }
    hikariSource = ds;
}
 
Example 7
Source File: DatabaseConfiguration.java    From ServiceCutter with Apache License 2.0 6 votes vote down vote up
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource() {
	log.debug("Configuring Datasource");
	if (dataSourcePropertyResolver.getProperty("url") == null && dataSourcePropertyResolver.getProperty("databaseName") == null) {
		log.error("Your database connection pool configuration is incorrect! The application" + " cannot start. Please check your Spring profile, current profiles are: {}",
				Arrays.toString(env.getActiveProfiles()));

		throw new ApplicationContextException("Database connection pool is not configured correctly");
	}
	HikariConfig config = new HikariConfig();
	config.setDataSourceClassName(dataSourcePropertyResolver.getProperty("dataSourceClassName"));
	if (StringUtils.isEmpty(dataSourcePropertyResolver.getProperty("url"))) {
		config.addDataSourceProperty("databaseName", dataSourcePropertyResolver.getProperty("databaseName"));
		config.addDataSourceProperty("serverName", dataSourcePropertyResolver.getProperty("serverName"));
	} else {
		config.addDataSourceProperty("url", dataSourcePropertyResolver.getProperty("url"));
	}
	config.addDataSourceProperty("user", dataSourcePropertyResolver.getProperty("username"));
	config.addDataSourceProperty("password", dataSourcePropertyResolver.getProperty("password"));

	if (metricRegistry != null) {
		config.setMetricRegistry(metricRegistry);
	}
	return new HikariDataSource(config);
}
 
Example 8
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 9
Source File: DataSourceConfig.java    From Spring with Apache License 2.0 6 votes vote down vote up
@Bean
public DataSource dataSource() {
    try {
        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) {
        return null;
    }
}
 
Example 10
Source File: SagaPersistenceLoader.java    From opensharding-spi-impl with Apache License 2.0 6 votes vote down vote up
private static DataSource initDataSource(final SagaPersistenceConfiguration persistenceConfiguration) {
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl(persistenceConfiguration.getUrl());
    config.setUsername(persistenceConfiguration.getUsername());
    config.setPassword(persistenceConfiguration.getPassword());
    config.setConnectionTimeout(persistenceConfiguration.getConnectionTimeoutMilliseconds());
    config.setIdleTimeout(persistenceConfiguration.getIdleTimeoutMilliseconds());
    config.setMaxLifetime(persistenceConfiguration.getMaxLifetimeMilliseconds());
    config.setMaximumPoolSize(persistenceConfiguration.getMaxPoolSize());
    config.setMinimumIdle(persistenceConfiguration.getMinPoolSize());
    config.addDataSourceProperty("useServerPrepStmts", Boolean.TRUE.toString());
    config.addDataSourceProperty("cachePrepStmts", "true");
    config.addDataSourceProperty("prepStmtCacheSize", 250);
    config.addDataSourceProperty("prepStmtCacheSqlLimit", 2048);
    config.addDataSourceProperty("useLocalSessionState", Boolean.TRUE.toString());
    config.addDataSourceProperty("rewriteBatchedStatements", Boolean.TRUE.toString());
    config.addDataSourceProperty("cacheResultSetMetadata", Boolean.TRUE.toString());
    config.addDataSourceProperty("cacheServerConfiguration", Boolean.TRUE.toString());
    config.addDataSourceProperty("elideSetAutoCommits", Boolean.TRUE.toString());
    config.addDataSourceProperty("maintainTimeStats", Boolean.FALSE.toString());
    config.addDataSourceProperty("netTimeoutForStreamingResults", 0);
    return new HikariDataSource(config);
}
 
Example 11
Source File: DatabaseConfiguration.java    From expper with GNU General Public License v3.0 5 votes vote down vote up
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Datasource");
    if (dataSourceProperties.getUrl() == null) {
        log.error("Your database connection pool configuration is incorrect! The application" +
                " cannot start. Please check your Spring profile, current profiles are: {}",
            Arrays.toString(env.getActiveProfiles()));

        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
    config.addDataSourceProperty("url", dataSourceProperties.getUrl());
    if (dataSourceProperties.getUsername() != null) {
        config.addDataSourceProperty("user", dataSourceProperties.getUsername());
    } else {
        config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user
    }
    if (dataSourceProperties.getPassword() != null) {
        config.addDataSourceProperty("password", dataSourceProperties.getPassword());
    } else {
        config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password
    }

    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
 
Example 12
Source File: HikariCpIT.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 13
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 14
Source File: Storage.java    From Kepler with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Storage(String host, int port, String username, String password, String db) {
    try {
        HikariConfig config = new HikariConfig();
        config.setDriverClassName("org.mariadb.jdbc.Driver");
        config.setJdbcUrl("jdbc:mariadb://" + host + ":" + port + "/" + db);
        config.setUsername(username);
        config.setPassword(password);

        config.setPoolName("processing");

        // No martinmine/Leon/other Habbotards, you don't know better.
        // Read up on this first, before commenting dumb shit
        // https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing
        // availableProcessors() already returns thread count on hyper-threaded processors
        // Thus we don't need the * 2 described there
        config.setMaximumPoolSize(Runtime.getRuntime().availableProcessors() + 1);
        config.setMinimumIdle(1);

        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        config.addDataSourceProperty("characterEncoding", "utf8");
        config.addDataSourceProperty("useUnicode", "true");
        config.addDataSourceProperty("useSSL", "false");
        config.addDataSourceProperty("serverTimezone", "UTC");
        config.addDataSourceProperty("sessionVariables", "sql_mode='STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'");

        this.ds = new HikariDataSource(config);
        this.isConnected = true;

    } catch (Exception ex) {
        Storage.logError(ex);
    }
}
 
Example 15
Source File: HikariConnectionFactory.java    From LuckPerms with MIT License 5 votes vote down vote up
protected void appendConfigurationInfo(HikariConfig config) {
    String address = this.configuration.getAddress();
    String[] addressSplit = address.split(":");
    address = addressSplit[0];
    String port = addressSplit.length > 1 ? addressSplit[1] : "3306";

    config.setDataSourceClassName(getDriverClass());
    config.addDataSourceProperty("serverName", address);
    config.addDataSourceProperty("port", port);
    config.addDataSourceProperty("databaseName", this.configuration.getDatabase());
    config.setUsername(this.configuration.getUsername());
    config.setPassword(this.configuration.getPassword());
}
 
Example 16
Source File: Bootstrap.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void load(Blade blade) {
    try {
        JetbrickTemplateEngine templateEngine = new JetbrickTemplateEngine();
        blade.templateEngine(templateEngine);

        HikariConfig config = new HikariConfig();

        String url                   = blade.env("jdbc.url", "");
        String username              = blade.env("jdbc.username", "");
        String password              = blade.env("jdbc.password", "");
        String cachePrepStmts        = blade.env("datasource.cachePrepStmts", "true");
        String prepStmtCacheSize     = blade.env("datasource.prepStmtCacheSize", "250");
        String prepStmtCacheSqlLimit = blade.env("datasource.prepStmtCacheSqlLimit", "2048");

        config.setJdbcUrl(url);
        config.setUsername(username);
        config.setPassword(password);
        config.addDataSourceProperty("cachePrepStmts", cachePrepStmts);
        config.addDataSourceProperty("prepStmtCacheSize", prepStmtCacheSize);
        config.addDataSourceProperty("prepStmtCacheSqlLimit", prepStmtCacheSqlLimit);

        HikariDataSource ds = new HikariDataSource(config);
        Anima.open(ds);
    } catch (Exception e) {
        System.out.println("Connection database fail");
    }
}
 
Example 17
Source File: DatabaseModule.java    From curiostack with MIT License 5 votes vote down vote up
@Provides
@Singleton
static DataSource dataSource(DatabaseConfig config) {
  HikariConfig hikari = new HikariConfig();
  hikari.setJdbcUrl(config.getJdbcUrl());
  hikari.setUsername(config.getUsername());
  hikari.setPassword(config.getPassword());
  hikari.addDataSourceProperty("logger", "com.mysql.cj.log.Slf4JLogger");
  hikari.addDataSourceProperty("maxLifetime", config.getConnectionMaxLifetime().getSeconds());
  hikari.addDataSourceProperty("cachePrepStmts", true);
  hikari.addDataSourceProperty("prepStmtCacheSize", 250);
  hikari.addDataSourceProperty("prepStmtCacheSqlLimit", 2048);
  hikari.addDataSourceProperty("useServerPrepStmts", true);
  hikari.addDataSourceProperty("useLocalSessionState", true);
  hikari.addDataSourceProperty("useLocalTransactionState", true);
  hikari.addDataSourceProperty("rewriteBatchedStatements", true);
  hikari.addDataSourceProperty("cacheResultSetMetadata", true);
  hikari.addDataSourceProperty("cacheServerConfiguration", true);
  hikari.addDataSourceProperty("elideSetAutoCommits", true);
  hikari.addDataSourceProperty("maintainTimeStats", false);
  hikari.addDataSourceProperty("queryInterceptors", "brave.mysql8.TracingQueryInterceptor");
  hikari.addDataSourceProperty(
      "exceptionInterceptors", "brave.mysql8.TracingExceptionInterceptor");
  hikari.setMetricsTrackerFactory(new PrometheusMetricsTrackerFactory());
  if (!config.getLeakDetectionThreshold().isZero()) {
    hikari.addDataSourceProperty(
        "leakDetectionThreshold", config.getLeakDetectionThreshold().getSeconds());
  }
  hikari.addDataSourceProperty("connectTimeout", config.getConnectTimeout().getSeconds());
  hikari.addDataSourceProperty("socketTimeout", config.getSocketTimeout().getSeconds());
  return new HikariDataSource(hikari);
}
 
Example 18
Source File: DatabaseManager.java    From BedwarsRel with GNU General Public License v3.0 5 votes vote down vote up
public void initialize() {
  HikariConfig config = new HikariConfig();
  config.setJdbcUrl("jdbc:mysql://" + this.host + ":" + String.valueOf(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 19
Source File: MySQL.java    From MySQL with MIT License 5 votes vote down vote up
/**
 * Creates a new MySQL instance for a specific database
 *
 * @param hostname | Name of the host
 * @param port     | Port number
 * @param database | Database name
 * @param username | Username
 * @param password | Password
 * @param params   | Extra parameters
 */
public MySQL(String hostname, String port, String database, String username, String password, String params) {

    // Build URL of database
    StringBuilder urlBuild = new StringBuilder();
    urlBuild.append("jdbc:mysql://");
    urlBuild.append(hostname);
    urlBuild.append(":");
    urlBuild.append(port);
    urlBuild.append("/");
    urlBuild.append(database);

    // Params to db url
    if (!params.isEmpty()) {

        if (!params.startsWith("?")) urlBuild.append("?");

        urlBuild.append(params);
    }

    // Begin configuration of Hikari DataSource
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl(urlBuild.toString());
    config.setUsername(username);
    config.setPassword(password);

    // See: https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
    config.addDataSourceProperty("cachePrepStmts", "true");
    config.addDataSourceProperty("prepStmtCacheSize", "250");
    config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
    config.addDataSourceProperty("useServerPrepStmts", "true");
    config.addDataSourceProperty("useLocalSessionState", "true");
    config.addDataSourceProperty("rewriteBatchedStatements", "true");
    config.addDataSourceProperty("cacheResultSetMetadata", "true");
    config.addDataSourceProperty("cacheServerConfiguration", "true");
    config.addDataSourceProperty("elideSetAutoCommits", "true");
    config.addDataSourceProperty("maintainTimeStats", "false");

    dataSource = new HikariDataSource(config);
}
 
Example 20
Source File: AuthStorage.java    From FastLogin with MIT License 4 votes vote down vote up
public AuthStorage(FastLoginCore<?, ?, ?> core, String host, int port, String databasePath,
                   HikariConfig config, boolean useSSL) {
    this.core = core;
    config.setPoolName(core.getPlugin().getName());

    ThreadFactory platformThreadFactory = core.getPlugin().getThreadFactory();
    if (platformThreadFactory != null) {
        config.setThreadFactory(platformThreadFactory);
    }

    String jdbcUrl = "jdbc:";
    if (config.getDriverClassName().contains("sqlite")) {
        String pluginFolder = core.getPlugin().getPluginFolder().toAbsolutePath().toString();
        databasePath = databasePath.replace("{pluginDir}", pluginFolder);

        jdbcUrl += "sqlite://" + databasePath;
        config.setConnectionTestQuery("SELECT 1");
        config.setMaximumPoolSize(1);

        //a try to fix https://www.spigotmc.org/threads/fastlogin.101192/page-26#post-1874647
        // format strings retrieved by the timestamp column to match them from MySQL
        config.addDataSourceProperty("date_string_format", "yyyy-MM-dd HH:mm:ss");

        // TODO: test first for compatibility
        // config.addDataSourceProperty("date_precision", "seconds");
    } else {
        jdbcUrl += "mysql://" + host + ':' + port + '/' + databasePath;

        // Require SSL on the server if requested in config - this will also verify certificate
        // Those values are deprecated in favor of sslMode
        config.addDataSourceProperty("useSSL", useSSL);
        config.addDataSourceProperty("requireSSL", useSSL);

        // prefer encrypted if possible
        config.addDataSourceProperty("sslMode", "PREFERRED");

        // adding paranoid hides hostname, username, version and so
        // could be useful for hiding server details
        config.addDataSourceProperty("paranoid", true);

        // enable MySQL specific optimizations
        // disabled by default - will return the same prepared statement instance
        config.addDataSourceProperty("cachePrepStmts", true);
        // default prepStmtCacheSize 25 - amount of cached statements
        config.addDataSourceProperty("prepStmtCacheSize", 250);
        // default prepStmtCacheSqlLimit 256 - length of SQL
        config.addDataSourceProperty("prepStmtCacheSqlLimit", 2048);
        // default false - available in newer versions caches the statements server-side
        config.addDataSourceProperty("useServerPrepStmts", true);
        // default false - prefer use of local values for autocommit and
        // transaction isolation (alwaysSendSetIsolation) should only be enabled if always use the set* methods
        // instead of raw SQL
        // https://forums.mysql.com/read.php?39,626495,626512
        config.addDataSourceProperty("useLocalSessionState", true);
        // rewrite batched statements to a single statement, adding them behind each other
        // only useful for addBatch statements and inserts
        config.addDataSourceProperty("rewriteBatchedStatements", true);
        // cache result metadata
        config.addDataSourceProperty("cacheResultSetMetadata", true);
        // cache results of show variables and collation per URL
        config.addDataSourceProperty("cacheServerConfiguration", true);
        // default false - set auto commit only if not matching
        config.addDataSourceProperty("elideSetAutoCommits", true);

        // default true - internal timers for idle calculation -> removes System.getCurrentTimeMillis call per query
        // Some platforms are slow on this and it could affect the throughput about 3% according to MySQL
        // performance gems presentation
        // In our case it can be useful to see the time in error messages
        // config.addDataSourceProperty("maintainTimeStats", false);
    }

    config.setJdbcUrl(jdbcUrl);
    this.dataSource = new HikariDataSource(config);
}