private void setupPool() { HikariConfig config = new HikariConfig(); config.setJdbcUrl("jdbc:mysql://" + this.credentials.getHostname() + ":" + this.credentials.getPort() + "/" + this.credentials.getDatabaseName()); config.setDriverClassName("com.mysql.jdbc.Driver"); config.setUsername(this.credentials.getUsername()); config.setPassword(this.credentials.getPassword()); config.setMinimumIdle(this.minimumConnections); config.setMaximumPoolSize(this.maximumConnections); config.setConnectionTimeout(this.connectionTimeout); try { this.dataSource = new HikariDataSource(config); } catch (Exception e) { Bukkit.getLogger().severe("[ZorahPractice] - Unable to establish MySQL connection, plugin disabled."); Bukkit.getServer().getPluginManager().disablePlugin(PracticePlugin.getInstance()); } }
@Test public void testHikariType() throws SQLException { DataSource ds = DataSourceBuilder.create().build( DataSourceConfigProperties.builder("pooling2").withPropertySource("test_build.properties").build()); assertNotNull(ds); assertEquals(HikariDataSource.class, ds.getClass()); assertEquals("jdbc:h2:mem:testdb", ((HikariDataSource) ds).getJdbcUrl()); assertEquals("sa", ((HikariDataSource) ds).getUsername()); assertEquals(2, ((HikariDataSource) ds).getMinimumIdle()); assertEquals(7, ((HikariDataSource) ds).getMaximumPoolSize()); assertEquals(1234L, ((HikariDataSource) ds).getConnectionTimeout()); assertEquals(DatabasePlatform.H2.getDriverClassName(), ((HikariDataSource) ds).getDriverClassName()); assertEquals(DatabasePlatform.H2.getValidationQuery(), ((HikariDataSource) ds).getConnectionTestQuery()); try (Connection c = ds.getConnection()) { assertNotNull(c); } }
@Bean(destroyMethod = "close") public DataSource dataSource() { HikariConfig dataSourceConfig = new HikariConfig(); dataSourceConfig.setDriverClassName(environment.getRequiredProperty("spring.datasource.driver-class-name")); dataSourceConfig.setJdbcUrl(environment.getRequiredProperty("spring.datasource.url")); dataSourceConfig.setUsername(environment.getRequiredProperty("spring.datasource.username")); dataSourceConfig.setPassword(environment.getRequiredProperty("spring.datasource.password")); dataSourceConfig.setMaximumPoolSize(Integer.parseInt(environment.getRequiredProperty("spring.datasource.maximumPoolSize"))); dataSourceConfig.setMinimumIdle(Integer.parseInt(environment.getRequiredProperty("spring.datasource.minimumIdle"))); dataSourceConfig.setMaxLifetime(Integer.parseInt(environment.getRequiredProperty("spring.datasource.maxLifetime"))); dataSourceConfig.setConnectionTimeout(Long.parseLong(environment.getRequiredProperty("spring.datasource.connectionTimeout"))); dataSourceConfig.setIdleTimeout(Long.parseLong(environment.getRequiredProperty("spring.datasource.idleTimeout"))); dataSourceConfig.addDataSourceProperty("poolName", environment.getRequiredProperty("spring.datasource.poolName")); dataSourceConfig.addDataSourceProperty("cachePrepStmts", "true"); dataSourceConfig.addDataSourceProperty("prepStmtCacheSize", "250"); dataSourceConfig.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); return new HikariDataSource(dataSourceConfig); }
@Test public void enableDatabaseSQLiteTest() { try { final HikariConfig config = new HikariConfig(); config.setDriverClassName("org.sqlite.JDBC"); config.setConnectionTestQuery("SELECT 1"); config.setJdbcUrl("jdbc:sqlite:PetBlocks.db"); config.setMaxLifetime(60000); config.setIdleTimeout(45000); config.setMaximumPoolSize(50); final HikariDataSource ds = new HikariDataSource(config); ds.close(); } catch (final Exception ex) { Logger.getLogger(this.getClass().getSimpleName()).log(Level.WARNING, "Failed to enable database.", ex); Assert.fail(); } }
@Test public void enableDatabaseMySQLTest() { try { final DB database = DB.newEmbeddedDB(3306); database.start(); try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/?user=root&password=")) { try (Statement statement = conn.createStatement()) { statement.executeUpdate("CREATE DATABASE db"); } } final HikariConfig config = new HikariConfig(); config.setDriverClassName("com.mysql.jdbc.Driver"); config.setConnectionTestQuery("SELECT 1"); config.setJdbcUrl("jdbc:mysql://localhost:3306/db"); config.setMaxLifetime(60000); config.setIdleTimeout(45000); config.setMaximumPoolSize(50); final HikariDataSource ds = new HikariDataSource(config); ds.close(); database.stop(); } catch (final Exception ex) { Logger.getLogger(this.getClass().getSimpleName()).log(Level.WARNING, "Failed to enable database.", ex); Assert.fail(); } }
/** * Initializes a new databaseConnectionContext for the given url, userName and password * * @param url url * @param userName userNames * @param password password */ private ExtensionHikariConnectionContext(String driver, String url, String userName, String password, SQlRetriever retriever) { super(); this.retriever = retriever; final HikariConfig config = new HikariConfig(); config.setDriverClassName(driver); config.setConnectionTestQuery("SELECT 1"); config.setJdbcUrl(url); if (userName != null) config.setUsername(userName); if (password != null) config.setPassword(password); config.addDataSourceProperty("cachePrepStmts", "true"); config.addDataSourceProperty("prepStmtCacheSize", "250"); config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); if (driver.equals(SQLITE_DRIVER)) config.setMaximumPoolSize(1); else config.setMaximumPoolSize(10); this.ds = new HikariDataSource(config); Logger.getLogger(this.getClass().getSimpleName()).log(Level.INFO, "Connected to " + url); }
@Bean public DataSource dataSource() { logger.debug("Configuring Datasource"); String databaseUrl = String.format("jdbc:mysql://%s:%s/%s?%s", databaseHostname, databasePort, databaseSchema, databaseOptions); logger.info("database.url:" + databaseUrl); logger.info("database.user:" + databaseUser); HikariConfig config = new HikariConfig(); config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource"); config.addDataSourceProperty("url", databaseUrl); config.addDataSourceProperty("user", databaseUser); config.setInitializationFailFast(false); config.setIdleTimeout(60000); String forcePassword = System.getenv("MYSQL_ROOT_PASSWORD"); // coming from environnment host if (forcePassword != null) { logger.info("Force the mysql password from host env"); databasePassword = forcePassword; } logger.info("URL : " + databaseUrl + " password : " + databasePassword); config.addDataSourceProperty("password", databasePassword); return new HikariDataSource(config); }
@Bean public DataSource dataSource() { logger.debug("Configuring Datasource"); String databaseUrl = String.format("jdbc:mysql://%s:%s/%s?%s", databaseHostname, databasePort, databaseSchema, databaseOptions); logger.debug("database.url:" + databaseUrl); logger.debug("database.user:" + databaseUser); HikariConfig config = new HikariConfig(); config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource"); config.addDataSourceProperty("url", databaseUrl); config.addDataSourceProperty("user", databaseUser); config.addDataSourceProperty("password", databasePassword); // config.setAutoCommit(false); return new HikariDataSource(config); }
@Test public void testDecoratedHikariSpecificPropertiesIsSet() throws Exception { EnvironmentTestUtils.addEnvironment(context, "spring.datasource.type:" + HikariDataSource.class.getName(), "spring.datasource.hikari.catalog:test_catalog"); context.register(DataSourceAutoConfiguration.class, DataSourceDecoratorAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); context.refresh(); DataSource dataSource = context.getBean(DataSource.class); assertThat(dataSource).isNotNull(); assertThat(dataSource).isInstanceOf(DecoratedDataSource.class); DataSource realDataSource = ((DecoratedDataSource) dataSource).getRealDataSource(); assertThat(realDataSource).isInstanceOf(HikariDataSource.class); assertThat(((HikariDataSource) realDataSource).getCatalog()).isEqualTo("test_catalog"); }
public static String getLastUrlForLastTime() { String urlForLastTime = null; final HikariDataSource mysqlDataSource = DataSource.getMysqlDataSource(); //从第二张数据表中取出已有所有论文相关指标页面链接 try (final Connection connection = mysqlDataSource.getConnection()) { try (final PreparedStatement preparedStatement = connection.prepareStatement("SELECT URL FROM NT_PAPERS LIMIT 1")) { try (ResultSet results = preparedStatement.executeQuery()) { while (results.next()) { urlForLastTime = results.getString("URL"); } } } } catch (SQLException e) { e.printStackTrace(); } return urlForLastTime; }
@Test public void testDecoratingHikariDataSourceWithDefaultStrategies() throws Exception { EnvironmentTestUtils.addEnvironment(context, "spring.datasource.type:" + HikariDataSource.class.getName()); context.register(DataSourceAutoConfiguration.class, DataSourceDecoratorAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); context.refresh(); DataSource dataSource = context.getBean(DataSource.class); assertDataSourceOfType(dataSource, HikariDataSource.class); FlexyPoolDataSource<HikariDataSource> flexyPoolDataSource = assertDataSourceOfType(dataSource, HikariDataSource.class); IncrementPoolOnTimeoutConnectionAcquiringStrategy strategy1 = findStrategy(flexyPoolDataSource, IncrementPoolOnTimeoutConnectionAcquiringStrategy.class); assertThat(strategy1).isNotNull(); assertThat(strategy1).hasFieldOrPropertyWithValue("maxOverflowPoolSize", 15); assertThat(strategy1).hasFieldOrPropertyWithValue("timeoutMillis", 500); RetryConnectionAcquiringStrategy strategy2 = findStrategy(flexyPoolDataSource, RetryConnectionAcquiringStrategy.class); assertThat(strategy2).isNotNull(); assertThat(strategy2).hasFieldOrPropertyWithValue("retryAttempts", 2); }
@Test public void testDecoratingHikariDataSourceWithCustomPropertyStrategies() throws Exception { EnvironmentTestUtils.addEnvironment(context, "spring.datasource.type:" + HikariDataSource.class.getName(), "decorator.datasource.flexy-pool.acquiring-strategy.increment-pool.max-overflow-pool-size:15", "decorator.datasource.flexy-pool.acquiring-strategy.increment-pool.timeout-millis:500", "decorator.datasource.flexy-pool.acquiring-strategy.retry.attempts:5"); context.register(DataSourceAutoConfiguration.class, DataSourceDecoratorAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, HikariConfiguration.class); context.refresh(); DataSource dataSource = context.getBean(DataSource.class); FlexyPoolDataSource<HikariDataSource> flexyPoolDataSource = assertDataSourceOfType(dataSource, HikariDataSource.class); IncrementPoolOnTimeoutConnectionAcquiringStrategy strategy1 = findStrategy(flexyPoolDataSource, IncrementPoolOnTimeoutConnectionAcquiringStrategy.class); assertThat(strategy1).isNotNull(); assertThat(strategy1).hasFieldOrPropertyWithValue("maxOverflowPoolSize", 35); assertThat(strategy1).hasFieldOrPropertyWithValue("timeoutMillis", 10000); RetryConnectionAcquiringStrategy strategy2 = findStrategy(flexyPoolDataSource, RetryConnectionAcquiringStrategy.class); assertThat(strategy2).isNotNull(); assertThat(strategy2).hasFieldOrPropertyWithValue("retryAttempts", 5); }
private void createBean(ConfigurableListableBeanFactory configurableListableBeanFactory, String prefixName, JdbcProperties jdbcProperties) { String jdbcUrl = jdbcProperties.getJdbcUrl(); checkArgument(!Strings.isNullOrEmpty(jdbcUrl), prefixName + " url is null or empty"); log.info("prefixName is {}, jdbc properties is {}", prefixName, jdbcProperties); HikariDataSource hikariDataSource = createHikariDataSource(jdbcProperties); DataSourceSpy dataSource = new DataSourceSpy(hikariDataSource); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); AnnotationTransactionAspect.aspectOf().setTransactionManager(transactionManager); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); register(configurableListableBeanFactory, dataSource, prefixName + "DataSource", prefixName + "Ds"); register(configurableListableBeanFactory, jdbcTemplate, prefixName + "JdbcTemplate", prefixName + "Jt"); register(configurableListableBeanFactory, transactionManager, prefixName + "TransactionManager", prefixName + "Tx"); }
@Test public void testDataSource() throws SQLException { assertNotNull(dataSource); assertTrue(dataSource instanceof HikariDataSource); try (Connection c = dataSource.getConnection()) { assertNotNull(c); try (ResultSet rs = c.createStatement().executeQuery("select str from testx where key=1")) { rs.next(); assertEquals("One", rs.getString(1)); } } }
@Test public void testDataSource() throws Exception { assertThat(dataSource).isNotNull(); HikariDataSource hikariDataSource = dataSource.unwrap(HikariDataSource.class); assertThat(hikariDataSource.getUsername()).isEqualTo("root"); assertThat(hikariDataSource.getPassword()).isEqualTo(""); assertThat(hikariDataSource.getJdbcUrl()).isEqualTo( "jdbc:log4jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false"); assertThat(hikariDataSource.isAutoCommit()).isEqualTo(false); assertThat(hikariDataSource.getConnectionTimeout()).isEqualTo(30000); assertThat(hikariDataSource.getIdleTimeout()).isEqualTo(600000); assertThat(hikariDataSource.getMaxLifetime()).isEqualTo(1800000); assertThat(hikariDataSource.getMaximumPoolSize()).isEqualTo(30); assertThat(hikariDataSource.getMinimumIdle()).isEqualTo(10); assertThat(hikariDataSource.getInitializationFailTimeout()).isEqualTo(1); assertThat(hikariDataSource.isIsolateInternalQueries()).isEqualTo(false); assertThat(hikariDataSource.isReadOnly()).isEqualTo(false); assertThat(hikariDataSource.isRegisterMbeans()).isEqualTo(false); assertThat(hikariDataSource.getDriverClassName()).isEqualTo(null); assertThat(hikariDataSource.getValidationTimeout()).isEqualTo(5000); assertThat(hikariDataSource.getLeakDetectionThreshold()).isEqualTo(0); }
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); }
public LoggingModule() throws DataException { setInstance(this); YamlConfiguration bukkitYml = YamlConfiguration .loadConfiguration(new File(Bukkit.getWorldContainer().getAbsoluteFile(), "bukkit.yml")); DB_URL = KingdomFactionsPlugin.getInstance().getDataManager().getString("Database.Logging.url").replace("{NAME}", DB_NAME); USERNAME = bukkitYml.getString("database.username"); PASSWORD = bukkitYml.getString("database.password"); datasource = new HikariDataSource(); datasource.setMaximumPoolSize(25); datasource.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource"); datasource.addDataSourceProperty("url", DB_URL); datasource.addDataSourceProperty("port", 3306); datasource.addDataSourceProperty("databaseName", DB_NAME); datasource.addDataSourceProperty("user", USERNAME); datasource.addDataSourceProperty("password", PASSWORD); insertQuery("CREATE DATABASE IF NOT EXISTS " + DB_NAME); }
public MySQLModule() { setInstance(this); YamlConfiguration bukkitYml = YamlConfiguration .loadConfiguration(new File(Bukkit.getWorldContainer().getAbsoluteFile(), "bukkit.yml")); DB_URL = bukkitYml.getString("database.url").replace("{NAME}", DB_NAME); USERNAME = bukkitYml.getString("database.username"); PASSWORD = bukkitYml.getString("database.password"); datasource = new HikariDataSource(); datasource.setMaximumPoolSize(25); datasource.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource"); datasource.addDataSourceProperty("url", DB_URL); datasource.addDataSourceProperty("port", 3306); datasource.addDataSourceProperty("databaseName", DB_NAME); datasource.addDataSourceProperty("user", USERNAME); datasource.addDataSourceProperty("password", PASSWORD); insertQuery("CREATE DATABASE IF NOT EXISTS " + DB_NAME); new PlayerDatabase(); new FactionDatabase(); new NexusDatabase(); new KingdomDatabase(); new BuildingDatabase(); new FactionHomeDatabase(); new ShopDatabase(); new ShopLogDatabase(); }
private static void openConnectionPool(String url, String driverClass, String username, String password) throws Exception { //force the driver to be loaded Class.forName(driverClass); HikariDataSource pool = new HikariDataSource(); pool.setJdbcUrl(url); pool.setUsername(username); pool.setPassword(password); pool.setMaximumPoolSize(4); pool.setMinimumIdle(1); pool.setIdleTimeout(60000); pool.setPoolName("Hl7MergeCheckerPool" + url); pool.setAutoCommit(false); connectionPool = pool; //test getting a connection Connection conn = pool.getConnection(); conn.close(); }
public Database() { try { Class.forName("org.mariadb.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } HikariConfig config = new HikariConfig(); config.setJdbcUrl(App.getConfig().getString("database.url")); config.setUsername(App.getConfig().getString("database.user")); config.setPassword(App.getConfig().getString("database.pass")); config.addDataSourceProperty("cachePrepStmts", "true"); config.addDataSourceProperty("prepStmtCacheSize", "250"); config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); config.addDataSourceProperty("allowMultiQueries", "true"); config.setMaximumPoolSize(200); // this is plenty, the websocket uses 32 dbi = new DBI(new HikariDataSource(config)); getHandle().createPixelsTable(); getHandle().createUsersTable(); getHandle().createSessionsTable(); getHandle().createAdminLogTable(); getHandle().createReportsTable(); }
@Override public void testConnection(String driverClass, String jdbcUrl, String username, String password) { try { HikariDataSource source = new HikariDataSource(); source.setDriverClassName(driverClass); source.setJdbcUrl(jdbcUrl); source.setUsername(username); source.setPassword(password); source.setMaximumPoolSize(1); String testQuery = "SELECT COUNT(*) FROM " + (jdbcUrl.startsWith("jdbc:oracle") ? "ALL_TABLES" : "information_schema.tables"); new JdbcTemplate(source).query(testQuery, IGNORE_ROWS); source.close(); } catch( Exception ex ) { LOGGER.warn("Test connection failure", ex); Throwable rootCause = Throwables.getRootCause(ex); throw new RuntimeException("Error attempting to connect or while executing test query: " + rootCause.getMessage()); } }
@Override public synchronized void prepare() { if(dataSource == null) { Properties properties = new Properties(); properties.putAll(configMap); HikariConfig config = new HikariConfigExt(properties); if(properties.containsKey("dataSource.url")) { LOG.info("DataSource Url: " + properties.getProperty("dataSource.url")); } else if (config.getJdbcUrl() != null) { LOG.info("JDBC Url: " + config.getJdbcUrl()); } this.dataSource = new HikariDataSource(config); this.dataSource.setAutoCommit(false); } }
private MySQLThreadPool(FileConfiguration config) { HikariConfig poolConf = new HikariConfig(); poolConf.setJdbcUrl("jdbc:mysql://" + config.getString("mysql.host", "localhost") + ":" + config.getInt("mysql.port", 3306) + "/" + config.getString("mysql.database", "Stats4") + config.getString("mysql.extra-opts", "")); poolConf.setUsername(config.getString("mysql.username")); poolConf.setPassword(config.getString("mysql.password")); poolConf.addDataSourceProperty("cachePrepStmts", true); poolConf.addDataSourceProperty("prepStmtCacheSize", "256"); poolConf.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); poolConf.addDataSourceProperty("useServerPrepStmts", true); poolConf.addDataSourceProperty("useLocalSessionState", true); poolConf.addDataSourceProperty("useLocalTransactionState", true); poolConf.addDataSourceProperty("rewriteBatchedStatements", true); poolConf.addDataSourceProperty("cacheResultSetMetadata", true); poolConf.addDataSourceProperty("cacheServerConfiguration", true); poolConf.addDataSourceProperty("elideSetAutoCommits", true); // poolConf.addDataSourceProperty("maintainTimeStats", false); this.dataSource = new HikariDataSource(poolConf); }
private static String getUpdateTime(){ try { String time=""; final HikariDataSource mysqlDataSource = DataSource.getMysqlDataSource(); final Connection connection = mysqlDataSource.getConnection(); final PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_TIME_SQL); ResultSet resultSet=preparedStatement.executeQuery(); while (resultSet.next()){ time=resultSet.getString(1); } System.out.println("当前是第"+time+"次爬取"); return time; } catch (SQLException e) { e.printStackTrace(); return "2"; } }
public static boolean executeChangeUpdateTimeSQL(){ try { final HikariDataSource mysqlDataSource = DataSource.getMysqlDataSource(); final Connection connection = mysqlDataSource.getConnection(); final PreparedStatement preparedStatement = connection.prepareStatement(CHANGE_UPDATE_TIME_SQL); preparedStatement.setString(1,getChangeUpdateTime()); preparedStatement.setString(2,Helper.getCrawlTime()); boolean isSuccessful=preparedStatement.executeUpdate()!=0; if (isSuccessful){ System.out.println("成功更新爬取次数"); } return isSuccessful; } catch (SQLException e) { e.printStackTrace(); System.out.println("更新爬取次数失败"); return false; } }
public static List<PaperMetricsLink> loadMetricsLinks() { List<PaperMetricsLink> paperMetricsLinks = new ArrayList<>(); final HikariDataSource mysqlDataSource = DataSource.getMysqlDataSource(); //从第二张数据表中取出已有所有论文相关指标页面链接 try (final Connection connection = mysqlDataSource.getConnection()) { try (final PreparedStatement preparedStatement = connection.prepareStatement("SELECT URL FROM REF_DATA")) { try (ResultSet results = preparedStatement.executeQuery()) { while (results.next()) { final String url = results.getString("URL"); paperMetricsLinks.add(new PaperMetricsLink(url)); } } } } catch (SQLException e) { System.out.println("Connected DB Failed"); } return paperMetricsLinks; }
@Test @Override public void test() { HikariDataSource dataSource = (HikariDataSource) this.dataSource; assertEquals("jdbc:mysql://google/test-database?cloudSqlInstance=proj:reg:test-instance" + "&socketFactory=com.google.cloud.sql.mysql.SocketFactory&useSSL=false", this.urlProvider.getJdbcUrl()); assertEquals("watchmaker", dataSource.getUsername()); assertEquals("pass", dataSource.getPassword()); assertEquals("com.mysql.jdbc.Driver", this.urlProvider.getJdbcDriverClass()); }
@Bean public DataSource primaryDataSource() { HikariDataSource ds = new HikariDataSource(); ds.setMaximumPoolSize(100); ds.setMinimumIdle(30); ds.setDriverClassName("org.h2.Driver"); ds.setJdbcUrl("jdbc:h2:mem:test"); ds.setUsername("root"); ds.setPassword("root"); return ds; }
/** * 测试构建默认的数据源. */ @Test public void testBuildDefaultDataSource() { HikariDataSource hds = dsBuilder.buildDefaultDataSource(props.getProperty("driver"), props.getProperty("url"), props.getProperty("username"), props.getProperty("password")); Assert.assertNotNull(hds); }
@Bean @Primary public DataSource getDataSource() { HikariConfig config = new HikariConfig(); config.setDriverClassName("com.mysql.jdbc.Driver"); config.setJdbcUrl("jdbc:mysql://localhost:3306/test"); config.setUsername("root"); config.setPassword("root"); config.setMaximumPoolSize(500); config.setMinimumIdle(10); return new HikariDataSource(config); }
public void connect() { dataSource = new HikariDataSource(); dataSource.setJdbcUrl(this.jdbcUrl); dataSource.setUsername(this.username); dataSource.setPassword(this.password); if (!doesTableExist("player_addresses")) { try (Connection connection = getConnection()) { PreparedStatement statement = connection.prepareStatement("CREATE TABLE player_addresses (`uuid` CHAR(36) PRIMARY KEY, `address` VARCHAR(20));"); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } }
public NodeAfterReceive(JSONObject m, ObjectOutputStream out, ExecutorService pool, HikariDataSource ds2) { super(); this.m = m; this.out = out; this.pool = pool; ds=ds2; }
@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("cachePrepStmts", "true"); hikari.addDataSourceProperty( "statementInterceptors", "brave.mysql.TracingStatementInterceptor"); hikari.addDataSourceProperty("useUnicode", "yes"); hikari.setMetricsTrackerFactory(new PrometheusMetricsTrackerFactory()); return new HikariDataSource(hikari); }
@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); }
public HikariDataSource create() { HikariDataSource ds = new HikariDataSource(); ds.addDataSourceProperty("cachePrepStmts", true); ds.addDataSourceProperty("prepStmtCacheSize", 250); ds.addDataSourceProperty("prepStmtCacheSqlLimit", 2048); ds.addDataSourceProperty("useServerPrepStmts", true); ds.setMaximumPoolSize(10); ds.setConnectionTimeout(5000); this.setPreDestory("close");// jBeanBox will close pool return ds; }
@Bean public DSLContext getDSLContext() { HikariDataSource hikariDataSource = new HikariDataSource(); hikariDataSource.setJdbcUrl(environment.getProperty("spring.datasource.url")); hikariDataSource.setUsername(environment.getProperty("spring.datasource.username")); hikariDataSource.setPassword(environment.getProperty("spring.datasource.password")); ConnectionProvider connectionProvider = new DataSourceConnectionProvider(hikariDataSource); org.jooq.Configuration configuration = new DefaultConfiguration().set(connectionProvider).set(SQLDialect.MYSQL); return DSL.using(configuration); }
@Test @Override public void test() { HikariDataSource dataSource = (HikariDataSource) this.dataSource; assertEquals("com.mysql.jdbc.GoogleDriver", this.urlProvider.getJdbcDriverClass()); assertEquals("com.mysql.jdbc.GoogleDriver", dataSource.getDriverClassName()); assertEquals("jdbc:google:mysql://tubular-bells:australia:test-instance/test-database", this.urlProvider.getJdbcUrl()); assertEquals("root", dataSource.getUsername()); assertEquals(null, dataSource.getPassword()); }
public static HikariDataSource createHikari(String url, String user, String pass, Properties dsProps) { HikariConfig config = new HikariConfig(); config.setJdbcUrl(url); config.setUsername(user); config.setPassword(pass); config.setDataSourceProperties(dsProps); LOGGER.info("creating hikaricp datasource. using jdbc url {}", config.getJdbcUrl()); return new HikariDataSource(config); }
public DatabaseConnectionPool(DatabaseProperties properties) { HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setDriverClassName("com.mysql.jdbc.Driver"); hikariConfig.setJdbcUrl(properties.getDatasourceUrl()); hikariConfig.setUsername(properties.getDatasourceUser()); hikariConfig.setPassword(properties.getDatasourcePassword()); hikariConfig.setConnectionInitSql(properties.getConnectionInitSql()); hikariConfig.addDataSourceProperty("cachePrepStmts", "true"); hikariConfig.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); hikariConfig.addDataSourceProperty("prepStmtCacheSize", "250"); hikariConfig.addDataSourceProperty("useServerPrepStmts", "true"); dataSource = new HikariDataSource(hikariConfig); }