@Primary @Bean(destroyMethod = "close") public DataSource dataSource() { final EmbeddedMysql embeddedMysql = embeddedMysql(); // make sure embeddedMySql is started. Map<String, String> params = ImmutableMap.<String, String>builder() .put("profileSQL", String.valueOf(false)) .put("generateSimpleParameterMetadata", String.valueOf(true)) .build(); final String url = String.format("jdbc:mysql://localhost:%d/%s?%s", embeddedMysql.getConfig().getPort(), SCHEMA_NAME, Joiner.on("&").withKeyValueSeparator("=").join(params)); DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create(); dataSourceBuilder.username(embeddedMysql.getConfig().getUsername()); dataSourceBuilder.password(embeddedMysql.getConfig().getPassword()); dataSourceBuilder.driverClassName(com.mysql.jdbc.Driver.class.getName()); dataSourceBuilder.url(url); return dataSourceBuilder.build(); }
@Bean public JdbcTemplate postgresJdbcTemplate( @Value("${postgres.jdbcUrl}") String postgresJdbcUrl, @Value("${postgres.jdbcDriver}") String postgresJdbcDriver, @Value("${postgres.jdbcUser}") String postgresJdbcUser, @Value("${postgres.jdbcPassword}") String postgresJdbcPassword) { DataSource targetDataSource = DataSourceBuilder .create() .driverClassName(postgresJdbcDriver) .url(postgresJdbcUrl) .username(postgresJdbcUser) .password(postgresJdbcPassword) .build(); return new JdbcTemplate(targetDataSource); }
/** * * @return экземпляр JDBCTemplate Для работы с тестовой базой данных */ public Database getFirstFunctionalInstance(){ if (firstFunctionalInstance == null) { LOG.debug("Инициируем новый инстанс базы данных"); DataSource ds = DataSourceBuilder .create() .username(databaseUser) .password(databasePassword) .url("jdbc:sqlserver://192.168.20.28:49484;instance=maindb") .driverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver") .build(); this.firstFunctionalInstance = new Database(ds); return firstFunctionalInstance; } else { LOG.debug("Инстанс базы данных уже инициирован, возвращаем существующий"); return firstFunctionalInstance;} }
public Database getFirstFunctionalInstance(String databaseName){ if (firstFunctionalInstance == null) { LOG.debug("Инициируем новый инстанс базы данных"); DataSource ds = DataSourceBuilder .create() .username(databaseUser) .password(databasePassword) .url("jdbc:sqlserver://192.168.20.28:49484;instance=maindb;databaseName="+databaseName) .driverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver") .build(); this.firstFunctionalInstance = new Database(ds); return firstFunctionalInstance; } else { LOG.debug("Инстанс базы данных уже инициирован, возвращаем существующий"); return firstFunctionalInstance;} }
/** * * @return экземпляр JDBCTemplate Для работы с базой данных нагрузочного стенда */ public Database getLoadInstance(){ if (loadInstance == null) { LOG.debug("Инициируем новый инстанс базы данных"); DataSource ds = DataSourceBuilder .create() .username(databaseUser) .password(databasePassword) .url("jdbc:sqlserver://192.168.21.9;instance=maindb") .driverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver") .build(); this.loadInstance = new Database(ds); return loadInstance; } else { LOG.debug("Инстанс базы данных уже инициирован, возвращаем существующий"); return loadInstance;} }
private void runScripts(List<Resource> resources, String username, String password) { if (resources.isEmpty()) { return; } ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.setContinueOnError(this.properties.isContinueOnError()); populator.setSeparator(this.properties.getSeparator()); if (this.properties.getSqlScriptEncoding() != null) { populator.setSqlScriptEncoding(this.properties.getSqlScriptEncoding().name()); } for (Resource resource : resources) { populator.addScript(resource); } DataSource dataSource = this.dataSource; if (StringUtils.hasText(username) && StringUtils.hasText(password)) { dataSource = DataSourceBuilder.create(this.properties.getClassLoader()) .driverClassName(this.properties.determineDriverClassName()) .url(this.properties.determineUrl()).username(username) .password(password).build(); } DatabasePopulatorUtils.execute(populator, dataSource); }
@Bean @ConfigurationProperties(prefix="spring.datasource.readonly") public DataSource readonlyDataSource() throws SQLException { DruidDataSource dataSource = (DruidDataSource)DataSourceBuilder .create() .type(DruidDataSource.class) .build(); // dataSource.setFilters("wall"); /* WallFilter wallFilter = new WallFilter(); wallFilter.setLogViolation(true); wallFilter.setThrowException(false); dataSource.getProxyFilters().add(wallFilter); */ return dataSource; }
@Bean(destroyMethod = "close") @ConditionalOnExpression("#{!environment.acceptsProfiles('" + Constants.SPRING_PROFILE_CLOUD + "') && !environment.acceptsProfiles('" + Constants.SPRING_PROFILE_HEROKU + "')}") @ConfigurationProperties(prefix = "spring.datasource.hikari") public DataSource dataSource(DataSourceProperties dataSourceProperties) { 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"); } HikariDataSource hikariDataSource = (HikariDataSource) DataSourceBuilder .create(dataSourceProperties.getClassLoader()) .type(HikariDataSource.class) .driverClassName(dataSourceProperties.getDriverClassName()) .url(dataSourceProperties.getUrl()) .username(dataSourceProperties.getUsername()) .password(dataSourceProperties.getPassword()) .build(); if (metricRegistry != null) { hikariDataSource.setMetricRegistry(metricRegistry); } return hikariDataSource; }
@Bean @org.springframework.boot.context.properties.ConfigurationProperties(prefix = "c2mon.server.configuration.jdbc") public DataSource configurationDataSource() { String url = properties.getJdbc().getUrl(); String username = properties.getJdbc().getUsername(); String password = properties.getJdbc().getPassword(); // A simple inspection is done on the JDBC URL to deduce whether to create an in-memory // in-process database, start a file-based externally visible database or connect to // an external database. if (url.contains("hsql")) { return new HsqlDatabaseBuilder() .url(url) .username(username) .password(password) .addScript(new ClassPathResource("sql/config-schema-hsqldb.sql")).build(); } else { return DataSourceBuilder.create().build(); } }
@Bean @ConfigurationProperties("c2mon.server.history.jdbc") public DataSource historyDataSource() { String url = properties.getJdbc().getUrl(); String username = properties.getJdbc().getUsername(); String password = properties.getJdbc().getPassword(); if (url.contains("hsql")) { return new HsqlDatabaseBuilder() .url(url) .username(username) .password(password) .addScript(new ClassPathResource("sql/history-schema-hsqldb.sql")).build(); } else { return DataSourceBuilder.create().build(); } }
public DataSource build() { DataSource dataSource; if (url == null || url.contains("hsqldb:mem")) { // Start an in-process, in-memory HSQL server dataSource = new EmbeddedDatabaseBuilder().setType(HSQL).setName("c2mondb").build(); } else if (url.contains("hsql://")) { // Start an externally visible, file-based HSQL server HsqlServer.start("file:///tmp/c2mondb", "c2mondb"); url += ";sql.syntax_ora=true;hsqldb.default_table_type=cached;hsqldb.cache_rows=1000;hsqldb.result_max_memory_rows=2000;hsqldb.cache_size=100"; dataSource = DataSourceBuilder.create().url(url).username(username).password(password).build(); } else { throw new RuntimeException("The given URL was not a valid HSQL JDBC URL!"); } if (!scripts.isEmpty()) { ResourceDatabasePopulator populator = new ResourceDatabasePopulator(scripts.toArray(new Resource[scripts.size()])); populator.setContinueOnError(true); DatabasePopulatorUtils.execute(populator, dataSource); } return dataSource; }
@Bean @ConfigurationProperties(prefix = "c2mon.server.cachedbaccess.jdbc") public DataSource cacheDataSource() { String url = properties.getJdbc().getUrl(); String username = properties.getJdbc().getUsername(); String password = properties.getJdbc().getPassword(); // A simple inspection is done on the JDBC URL to deduce whether to create an in-memory // in-process database, start a file-based externally visible database or connect to // an external database. if (url.contains("hsql")) { return new HsqlDatabaseBuilder() .url(url) .username(username) .password(password) .addScript(new ClassPathResource("sql/cache-schema-hsqldb.sql")).build(); } else { return DataSourceBuilder.create().build(); } }
/** * 创建DataSource */ @SuppressWarnings("unchecked") public DataSource buildDataSource(Map<String, Object> dsMap) { try { Object type = dsMap.get("type"); if (type == null) type = DATASOURCE_TYPE_DEFAULT;// 默认DataSource Class<? extends DataSource> dataSourceType; dataSourceType = (Class<? extends DataSource>) Class.forName((String) type); String driverClassName = dsMap.get("driverClassName").toString(); String url = dsMap.get("url").toString(); String username = dsMap.get("username").toString(); String password = dsMap.get("password").toString(); DataSourceBuilder factory = DataSourceBuilder.create().driverClassName(driverClassName).url(url) .username(username).password(password).type(dataSourceType); return factory.build(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; }
/** * 创建DataSource * * @param type * @param driverClassName * @param url * @param username * @param password * @return * @author SHANHY * @create 2016年1月24日 */ @SuppressWarnings("unchecked") public DataSource buildDataSource(Map<String, Object> dsMap) { try { Object type = dsMap.get("type"); if (type == null) type = DATASOURCE_TYPE_DEFAULT;// 默认DataSource Class<? extends DataSource> dataSourceType; dataSourceType = (Class<? extends DataSource>) Class.forName((String) type); String driverClassName = dsMap.get("driver-class-name").toString(); String url = dsMap.get("url").toString(); String username = dsMap.get("username").toString(); String password = dsMap.get("password").toString(); DataSourceBuilder factory = DataSourceBuilder.create().driverClassName(driverClassName).url(url) .username(username).password(password).type(dataSourceType); return factory.build(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; }
@Bean public DataSource dataSourceProd() { String databaseUrl = env.getProperty("database.url"); String databaseUsername = env.getProperty("database.username"); String databasePassword = env.getProperty("database.password"); if(databaseUrl == null || databaseUsername == null || databasePassword == null) { logger.log(Level.ALL, "Using local H2 database"); return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build(); } logger.log(Level.ALL, "Using database " + databaseUrl); return DataSourceBuilder.create() .url(databaseUrl) .username(databaseUsername) .password(databasePassword) .build(); }
@Bean @Profile("default") public DataSource defaultDataSource() { String jdbcUrl = dataSourceUrl; if (jdbcUrl.isEmpty()) { jdbcUrl = "jdbc:hsqldb:file:" + getDatabaseDirectory() + ";create=true;hsqldb.tx=mvcc;hsqldb.applog=1;hsqldb.sqllog=0;hsqldb.write_delay=false"; } return DataSourceBuilder.create() .username(dataSourceUsername) .password(dataSourcePassword) .url(jdbcUrl) .driverClassName(dataSourceDriverClassName) .build(); }
/** * Get data source. * * @return Data source */ @Primary @Bean @ConfigurationProperties(prefix="spring.datasource") public DataSource getDatasource() { return DataSourceBuilder.create().build(); }
@Bean(name="writeDataSource", destroyMethod = "close", initMethod="init") @Primary @ConfigurationProperties(prefix = "spring.datasource") public DataSource writeDataSource() { logger.info("初始化写入数据源……"); return DataSourceBuilder.create().type(dataSourceType).build(); }
/** * 有多少个从库就要配置多少个 * @return */ @Bean(name = "readDataSource") @ConfigurationProperties(prefix = "custom.datasource.read") public DataSource readDataSource(){ logger.info("初始化读数据源……"); return DataSourceBuilder.create().type(dataSourceType).build(); }
@Bean @Primary public DataSource dataSource() { DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create(); dataSourceBuilder.driverClassName(org.sqlite.JDBC.class.getName()); dataSourceBuilder.url("jdbc:sqlite:~amv-access-test.db?journal_mode=wal"); return dataSourceBuilder.build(); }
@Bean @Primary public DataSource dataSource() { DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create(); dataSourceBuilder.driverClassName(org.sqlite.JDBC.class.getName()); dataSourceBuilder.url("jdbc:sqlite:~amv-access-swagger-docs.db?journal_mode=wal"); return dataSourceBuilder.build(); }
@Bean(name = "writeDataSource", destroyMethod = "close", initMethod = "init") @Primary @ConfigurationProperties(prefix = "spring.datasource") public DataSource writeDataSource() { log.info("-------------------- writeDataSource init ---------------------"); return DataSourceBuilder.create().type(dataSourceType).build(); }
@Bean @ConfigurationProperties(DruidProperties.DRUID_PREFIX) public DataSource dataSource(DruidProperties properties) { DruidDataSource datasource = (DruidDataSource) DataSourceBuilder .create() .type(DruidDataSource.class) .build(); configDruid(datasource, properties); return datasource; }
@Bean @ConfigurationProperties("calcite.datasource") public DataSource calciteDataSource(@Autowired String inlineModel) { DataSource dataSource = DataSourceBuilder .create() .driverClassName("org.apache.calcite.jdbc.Driver") .url("jdbc:calcite:lex=JAVA;model=inline:" + inlineModel) .build(); log.info("Generated Calcite mode: " + inlineModel); return dataSource; }
/** * 主库配置(负责写) * @return */ @Bean(name="masterDataSource") @Primary @ConfigurationProperties(prefix = "spring.datasource") public DataSource writeDataSource() { log.info("-------------------- Master DataSource init ---------------------"); return DataSourceBuilder.create().type(dataSourceType).build(); }
/** * 主库配置(负责写) * @return */ @Bean(name="masterDataSource", destroyMethod = "close", initMethod="init") @Primary @ConfigurationProperties(prefix = "spring.datasource",locations = "classpath:application.properties") public DataSource writeDataSource() { log.info("-------------------- Master DataSource init ---------------------"); return DataSourceBuilder.create().type(dataSourceType).build(); }
/** * 从库配置(负责读) * @return */ @Bean(name = "slaveDataSourceOne") @ConfigurationProperties(prefix = "spring.slave",locations = "classpath:application.properties") public DataSource readDataSourceOne(){ log.info("-------------------- Slave DataSource One init ---------------------"); return DataSourceBuilder.create().type(dataSourceType).build(); }
@Bean(name = "dataSource") public DataSource getDataSource() { DataSource dataSource = DataSourceBuilder .create() .username(username) .password(password) .url(url) .driverClassName(driverClassName) .build(); return dataSource; }
@Bean @Primary @ConfigurationProperties(prefix = "spring.datasource") public DataSource activitiDataSource() { logger.debug("creating activitiDataSource bean"); return DataSourceBuilder.create().build(); }
private DataSource getDataSource() { if (this.myBatisMigrationsDataSource != null) { return this.myBatisMigrationsDataSource; } if (this.properties.getUrl() == null) { return this.dataSource; } return DataSourceBuilder.create().url(this.properties.getUrl()) .username(this.properties.getUser()) .password(this.properties.getPassword()).build(); }
@Bean @Primary @ConfigurationProperties(prefix = "spring.datasource") public DataSource dataSource() { ConnectionData conData = getDbUrl(); return DataSourceBuilder .create() .url(conData.getUrl() + "?sslmode=require") .username(conData.getUser()) .password(conData.getPassword()) .driverClassName("org.postgresql.Driver") .build(); }
@Bean @Primary @Qualifier("jpaDataSource") @ConfigurationProperties(prefix = "spring.datasource") public DataSource createJpaDataSource() { return DataSourceBuilder.create().type(dataSourceType).build(); }
/** * Activiti's user guide - 5.7.3. Changing the database and connection pool * https://www.activiti.org/userguide/index.html#_changing_the_database_and_connection_pool **/ @Bean(name = "datasource.activiti") public DataSource activitiDataSource() { return DataSourceBuilder.create(this.dataSourceproperties.getClassLoader()) .url(this.dataSourceproperties.getUrl()) .username(this.dataSourceproperties.getUsername()) .password(this.dataSourceproperties.getPassword()) .driverClassName(this.dataSourceproperties.getDriverClassName()) .build(); }
/** * @param dataSourceClassType * @return * @Title: buildDataSource * @Description: 根据数据源class类型创建数据源 * @author Kola 6089555 * @date 2017年4月24日 下午6:46:47 */ @SuppressWarnings("unchecked") public DataSource buildDataSource(String dataSourceClassType) { DataSource dataSource = null; try { if (StringUtils.isBlank(dataSourceClassType)) dataSourceClassType = DATASOURCE_TYPE_DEFAULT; Class<? extends DataSource> dataSourceType = (Class<? extends DataSource>) Class.forName(dataSourceClassType); dataSource = DataSourceBuilder.create().type(dataSourceType).build(); } catch (ClassNotFoundException e) { LOGGER.error("buildDataSource failure.because {}", e.getMessage()); e.printStackTrace(); } return dataSource; }
@Bean public DataSource getDataSource() { return DataSourceBuilder .create() .driverClassName("org.hsqldb.jdbcDriver") .url("jdbc:hsqldb:file:" + new File(Utils.getBase(), "db").getPath() + "/store") .username("iisi") .password("") .build(); }