Java Code Examples for com.alibaba.druid.pool.DruidDataSource#init()

The following examples show how to use com.alibaba.druid.pool.DruidDataSource#init() . 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: StaticTAtomDataSource.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
public void doInit() throws TddlException {
    try {
        DruidDataSource localDruidDataSource = TAtomDsConfHandle.convertTAtomDsConf2DruidConf(confDO.getIp(),
            confDO,
            confDO.getDbName());
        boolean checkPram = TAtomDsConfHandle.checkLocalTxDataSourceDO(localDruidDataSource);
        if (checkPram) {
            localDruidDataSource.init();
            druidDataSource = localDruidDataSource;
        } else {
            throw new TddlException(ErrorCode.ERR_CONFIG, "atom config check failed");
        }
    } catch (Exception e) {
        throw new TddlNestableRuntimeException(e);
    }
}
 
Example 2
Source File: DynamicDataSource.java    From galaxy with Apache License 2.0 6 votes vote down vote up
private DataSource getDruidDataSource(DataSourceInfoDto dto) {
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setUrl(dto.getDbUrl());
    druidDataSource.setUsername(dto.getUsername());
    druidDataSource.setPassword(getPassword(dto.getUsername(), dto.getPassword()));
    druidDataSource.setMaxActive(dto.getMaxActive());
    druidDataSource.setInitialSize(dto.getInitialSize());
    druidDataSource.setMaxWait(60000);
    druidDataSource.setTimeBetweenEvictionRunsMillis(300000);
    druidDataSource.setMinEvictableIdleTimeMillis(300000);
    druidDataSource.setValidationQuery("select 1");
    druidDataSource.setTestWhileIdle(true);
    druidDataSource.setTestOnBorrow(false);
    druidDataSource.setTestOnReturn(false);
    druidDataSource.setPoolPreparedStatements(true);
    druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(50);
    try {
        druidDataSource.init();
    } catch (SQLException e) {
        log.error("Can't init druidDataSource from DataSourceInfo:" + dto, e);
    }
    return druidDataSource;
}
 
Example 3
Source File: JDBCTransactionStore.java    From rocketmq_trans_message with Apache License 2.0 6 votes vote down vote up
@Override
public boolean load() {
    try {
        druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(messageStoreConfig.getJdbcDriverClass());
        druidDataSource.setUrl(messageStoreConfig.getJdbcURL());
        druidDataSource.setUsername(messageStoreConfig.getJdbcUser());
        druidDataSource.setPassword(messageStoreConfig.getJdbcPassword());
        druidDataSource.setInitialSize(5);
        druidDataSource.setMaxActive(10);
        druidDataSource.setMinIdle(5);
        druidDataSource.setMaxWait(2000);
        druidDataSource.setMinEvictableIdleTimeMillis(300000);
        druidDataSource.setUseUnfairLock(true);
        druidDataSource.setConnectionErrorRetryAttempts(3);
        druidDataSource.setValidationQuery("SELECT 'x'");
        druidDataSource.setTestOnReturn(false);
        druidDataSource.setTestOnBorrow(false);
        druidDataSource.init();
        return true;
    } catch (Exception e) {
        log.info("druidDataSource load Exeption", e);
        return false;
    }
}
 
Example 4
Source File: ResourceFactory.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void internal_driud() throws Exception {
	for (Entry<String, DataServer> entry : Config.nodes().dataServers().entrySet()) {
		DruidDataSource dataSource = new DruidDataSource();
		String url = "jdbc:h2:tcp://" + entry.getKey() + ":" + entry.getValue().getTcpPort() + "/X;JMX="
				+ (entry.getValue().getJmxEnable() ? "TRUE" : "FALSE") + ";CACHE_SIZE="
				+ (entry.getValue().getCacheSize() * 1024);
		dataSource.setDriverClassName(SlicePropertiesBuilder.driver_h2);
		dataSource.setUrl(url);
		dataSource.setInitialSize(0);
		dataSource.setMinIdle(0);
		dataSource.setMaxActive(50);
		dataSource.setUsername("sa");
		dataSource.setTestWhileIdle(false);
		dataSource.setTestOnReturn(false);
		dataSource.setTestOnBorrow(false);
		dataSource.setFilters("stat");
		dataSource.setPassword(Config.token().getPassword());
		dataSource.init();
		String name = Config.nodes().dataServers().name(entry.getValue());
		new Resource(Config.RESOURCE_JDBC_PREFIX + name, dataSource);
	}
}
 
Example 5
Source File: IDGenServiceTest.java    From Leaf with Apache License 2.0 6 votes vote down vote up
@Before
public void before() throws IOException, SQLException {
    // Load Db Config
    Properties properties = PropertyFactory.getProperties();

    // Config dataSource
    dataSource = new DruidDataSource();
    dataSource.setUrl(properties.getProperty("jdbc.url"));
    dataSource.setUsername(properties.getProperty("jdbc.username"));
    dataSource.setPassword(properties.getProperty("jdbc.password"));
    dataSource.init();

    // Config Dao
    IDAllocDao dao = new IDAllocDaoImpl(dataSource);

    // Config ID Gen
    idGen = new SegmentIDGenImpl();
    ((SegmentIDGenImpl) idGen).setDao(dao);
    idGen.init();
}
 
Example 6
Source File: DbRemoteConfigLoader.java    From canal-1.1.3 with Apache License 2.0 6 votes vote down vote up
public DbRemoteConfigLoader(String driverName, String jdbcUrl, String jdbcUsername, String jdbcPassword){
    dataSource = new DruidDataSource();
    if (StringUtils.isEmpty(driverName)) {
        driverName = "com.mysql.jdbc.Driver";
    }
    dataSource.setDriverClassName(driverName);
    dataSource.setUrl(jdbcUrl);
    dataSource.setUsername(jdbcUsername);
    dataSource.setPassword(jdbcPassword);
    dataSource.setInitialSize(1);
    dataSource.setMinIdle(1);
    dataSource.setMaxActive(1);
    dataSource.setMaxWait(60000);
    dataSource.setTimeBetweenEvictionRunsMillis(60000);
    dataSource.setMinEvictableIdleTimeMillis(300000);
    try {
        dataSource.init();
    } catch (SQLException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 7
Source File: DbRemoteConfigLoader.java    From canal with Apache License 2.0 6 votes vote down vote up
public DbRemoteConfigLoader(String driverName, String jdbcUrl, String jdbcUsername, String jdbcPassword){
    dataSource = new DruidDataSource();
    if (StringUtils.isEmpty(driverName)) {
        driverName = "com.mysql.jdbc.Driver";
    }
    dataSource.setDriverClassName(driverName);
    dataSource.setUrl(jdbcUrl);
    dataSource.setUsername(jdbcUsername);
    dataSource.setPassword(jdbcPassword);
    dataSource.setInitialSize(1);
    dataSource.setMinIdle(1);
    dataSource.setMaxActive(1);
    dataSource.setMaxWait(60000);
    dataSource.setTimeBetweenEvictionRunsMillis(60000);
    dataSource.setMinEvictableIdleTimeMillis(300000);
    try {
        dataSource.init();
    } catch (SQLException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 8
Source File: AdapterCanalConfig.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("resource")
public void setSrcDataSources(Map<String, DatasourceConfig> srcDataSources) {
    this.srcDataSources = srcDataSources;

    if (srcDataSources != null) {
        for (Map.Entry<String, DatasourceConfig> entry : srcDataSources.entrySet()) {
            DatasourceConfig datasourceConfig = entry.getValue();
            // 加载数据源连接池
            DruidDataSource ds = new DruidDataSource();
            ds.setDriverClassName(datasourceConfig.getDriver());
            ds.setUrl(datasourceConfig.getUrl());
            ds.setUsername(datasourceConfig.getUsername());
            ds.setPassword(datasourceConfig.getPassword());
            ds.setInitialSize(1);
            ds.setMinIdle(1);
            ds.setMaxActive(datasourceConfig.getMaxActive());
            ds.setMaxWait(60000);
            ds.setTimeBetweenEvictionRunsMillis(60000);
            ds.setMinEvictableIdleTimeMillis(300000);
            ds.setValidationQuery("select 1");
            try {
                ds.init();
            } catch (SQLException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
            DatasourceConfig.DATA_SOURCES.put(entry.getKey(), ds);
        }
    }
}
 
Example 9
Source File: DynamicDataSourceFactory.java    From spring-boot-study with MIT License 5 votes vote down vote up
/**
 * 通过自定义建立 Druid的数据源
 * */
public static DruidDataSource buildDruidDataSource(DataSourceProperties properties) {
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setDriverClassName(properties.getDriverClassName());
    druidDataSource.setUrl(properties.getUrl());
    druidDataSource.setUsername(properties.getUsername());
    druidDataSource.setPassword(properties.getPassword());

    druidDataSource.setInitialSize(properties.getInitialSize());
    druidDataSource.setMaxActive(properties.getMaxActive());
    druidDataSource.setMinIdle(properties.getMinIdle());
    druidDataSource.setMaxWait(properties.getMaxWait());
    druidDataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
    druidDataSource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis());
    druidDataSource.setMaxEvictableIdleTimeMillis(properties.getMaxEvictableIdleTimeMillis());
    druidDataSource.setValidationQuery(properties.getValidationQuery());
    druidDataSource.setValidationQueryTimeout(properties.getValidationQueryTimeout());
    druidDataSource.setTestOnBorrow(properties.isTestOnBorrow());
    druidDataSource.setTestOnReturn(properties.isTestOnReturn());
    druidDataSource.setPoolPreparedStatements(properties.isPoolPreparedStatements());
    druidDataSource.setMaxOpenPreparedStatements(properties.getMaxOpenPreparedStatements());
    druidDataSource.setSharePreparedStatements(properties.isSharePreparedStatements());

    try {
        druidDataSource.setFilters(properties.getFilters());
        druidDataSource.init();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return druidDataSource;
}
 
Example 10
Source File: DruidConfig.java    From mykit-delay with Apache License 2.0 5 votes vote down vote up
public DataSource newInstanceDruidDataSource() throws Exception {
    if (mydataSource != null) {
        return mydataSource;
    }
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setUrl(this.url);
    druidDataSource.setUsername(this.username);
    druidDataSource.setPassword(this.password);
    druidDataSource.setDriverClassName(this.driverClassName);
    druidDataSource.setInitialSize(this.initialSize);
    druidDataSource.setMaxActive(this.maxActive);
    druidDataSource.setMinIdle(this.minIdle);
    druidDataSource.setMaxWait(this.maxWait);
    druidDataSource.setTimeBetweenEvictionRunsMillis(this.timeBetweenEvictionRunsMillis);
    druidDataSource.setMinEvictableIdleTimeMillis(this.minEvictableIdleTimeMillis);
    druidDataSource.setValidationQuery(this.validationQuery);
    druidDataSource.setTestWhileIdle(this.testWhileIdle);
    druidDataSource.setTestOnBorrow(this.testOnBorrow);
    druidDataSource.setTestOnReturn(this.testOnReturn);
    druidDataSource.setPoolPreparedStatements(this.poolPreparedStatements);
    druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(this.maxPoolPreparedStatementPerConnectionSize);
    druidDataSource.setFilters(this.filters);

    try {
        if (null != druidDataSource) {
            druidDataSource.setFilters("wall,stat");
            druidDataSource.setUseGlobalDataSourceStat(true);
            druidDataSource.init();
        }
    } catch (Exception e) {
        throw new RuntimeException("load datasource error, dbProperties is :", e);
    }
    synchronized (this) {
        mydataSource = druidDataSource;
    }
    druidDataSource.init();
    return druidDataSource;
}
 
Example 11
Source File: DruidConfig.java    From sdmq with Apache License 2.0 5 votes vote down vote up
public DataSource newInstanceDruidDataSource() throws Exception {
    if (mydataSource != null) {
        return mydataSource;
    }
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setUrl(this.url);
    druidDataSource.setUsername(this.username);
    druidDataSource.setPassword(this.password);
    druidDataSource.setDriverClassName(this.driverClassName);
    druidDataSource.setInitialSize(this.initialSize);
    druidDataSource.setMaxActive(this.maxActive);
    druidDataSource.setMinIdle(this.minIdle);
    druidDataSource.setMaxWait(this.maxWait);
    druidDataSource.setTimeBetweenEvictionRunsMillis(this.timeBetweenEvictionRunsMillis);
    druidDataSource.setMinEvictableIdleTimeMillis(this.minEvictableIdleTimeMillis);
    druidDataSource.setValidationQuery(this.validationQuery);
    druidDataSource.setTestWhileIdle(this.testWhileIdle);
    druidDataSource.setTestOnBorrow(this.testOnBorrow);
    druidDataSource.setTestOnReturn(this.testOnReturn);
    druidDataSource.setPoolPreparedStatements(this.poolPreparedStatements);
    druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(this.maxPoolPreparedStatementPerConnectionSize);
    druidDataSource.setFilters(this.filters);

    try {
        if (null != druidDataSource) {
            druidDataSource.setFilters("wall,stat");
            druidDataSource.setUseGlobalDataSourceStat(true);
            druidDataSource.init();
        }
    } catch (Exception e) {
        throw new RuntimeException("load datasource error, dbProperties is :", e);
    }
    synchronized (this) {
        mydataSource = druidDataSource;
    }
    druidDataSource.init();
    return druidDataSource;
}
 
Example 12
Source File: SegmentService.java    From SpringMVC-Project with MIT License 5 votes vote down vote up
public SegmentService() throws SQLException, InitException {
    Properties properties = PropertyFactory.getProperties();
    boolean flag = Boolean.parseBoolean(properties.getProperty(Constants.LEAF_SEGMENT_ENABLE, "true"));
    if (flag) {
        // Config dataSource
        dataSource = new DruidDataSource();
        dataSource.setUrl(properties.getProperty(Constants.LEAF_JDBC_URL));
        dataSource.setUsername(properties.getProperty(Constants.LEAF_JDBC_USERNAME));
        dataSource.setPassword(properties.getProperty(Constants.LEAF_JDBC_PASSWORD));
        dataSource.init();

        // Config Dao
        IDAllocDao dao = new IDAllocDaoImpl(dataSource);

        // Config ID Gen
        idGen = new SegmentIDGenImpl();
        ((SegmentIDGenImpl) idGen).setDao(dao);
        if (idGen.init()) {
            logger.info("Segment Service Init Successfully");
        } else {
            throw new InitException("Segment Service Init Fail");
        }
    } else {
        idGen = new ZeroIDGen();
        logger.info("Zero ID Gen Service Init Successfully");
    }
}
 
Example 13
Source File: DbConfiguration.java    From flower with Apache License 2.0 5 votes vote down vote up
@Bean("dataSource")
public DruidDataSource getDataSource() throws SQLException {
  DruidDataSource dataSource = new DruidDataSource();
  dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
  dataSource.setUrl("jdbc:mysql://localhost:3306/flower?characterEncoding=UTF-8&serverTimezone=GMT%2B8");
  dataSource.setUsername("root");
  dataSource.setPassword("flower123");
  dataSource.setInitialSize(5);
  dataSource.setMaxActive(30);
  dataSource.setValidationQuery("select version()");
  dataSource.init();
  return dataSource;
}
 
Example 14
Source File: DruidIT.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws InterruptedException, SQLException {

    DruidDataSource dataSource = new DruidDataSource();

    dataSource.setUrl(JDBC_URL);
    dataSource.setValidationQuery("select 'x'");
    dataSource.setUsername("test");
    dataSource.setPassword("test");

    dataSource.init();
    try {
        Connection connection = dataSource.getConnection();
        Assert.assertNotNull(connection);

        connection.close();

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

        verifier.verifyTrace(event(serviceType, getConnectionMethod));
        verifier.verifyTrace(event(serviceType, closeConnectionMethod));
    } finally {
        if (dataSource != null) {
            dataSource.close();
        }
    }
}
 
Example 15
Source File: AdapterCanalConfig.java    From canal with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("resource")
public void setSrcDataSources(Map<String, DatasourceConfig> srcDataSources) {
    this.srcDataSources = srcDataSources;

    if (srcDataSources != null) {
        for (Map.Entry<String, DatasourceConfig> entry : srcDataSources.entrySet()) {
            DatasourceConfig datasourceConfig = entry.getValue();
            // 加载数据源连接池
            DruidDataSource ds = new DruidDataSource();
            ds.setDriverClassName(datasourceConfig.getDriver());
            ds.setUrl(datasourceConfig.getUrl());
            ds.setUsername(datasourceConfig.getUsername());
            ds.setPassword(datasourceConfig.getPassword());
            ds.setInitialSize(1);
            ds.setMinIdle(1);
            ds.setMaxActive(datasourceConfig.getMaxActive());
            ds.setMaxWait(60000);
            ds.setTimeBetweenEvictionRunsMillis(60000);
            ds.setMinEvictableIdleTimeMillis(300000);
            ds.setValidationQuery("select 1");
            try {
                ds.init();
            } catch (SQLException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
            DatasourceConfig.DATA_SOURCES.put(entry.getKey(), ds);
        }
    }
}
 
Example 16
Source File: DbNodeServiceImpl.java    From pmq with Apache License 2.0 5 votes vote down vote up
public void initDataSource(DbNodeEntity t1, String key, Map<String, DataSource> dataMap, boolean isMaster,
		Transaction transaction) {
	try {
		// if (soaConfig.isUseDruid())
		{
			DruidDataSource dataSource = dataSourceFactory.createDataSource();
			dataSource.setDriverClassName("com.mysql.jdbc.Driver");
			if (isMaster) {
				dataSource.setUsername(t1.getDbUserName());
				dataSource.setPassword(t1.getDbPass());
			} else {
				dataSource.setUsername(t1.getDbUserNameBak());
				dataSource.setPassword(t1.getDbPassBak());
			}
			// dataSource.setUrl(t1.getConStr());
			dataSource.setUrl(getCon(t1, isMaster));
			dataSource.setInitialSize(soaConfig.getInitDbCount());
			dataSource.setMinIdle(soaConfig.getInitDbCount());
			dataSource.setMaxActive(soaConfig.getMaxDbCount());
			dataSource.setConnectionInitSqls(Arrays.asList("set names utf8mb4;"));
			dataSource.init();
			dbCreated.put(key, true);
			log.info(dataSource.getUrl() + "数据源创建成功!dataSource_created");
			dataMap.put(key, dataSource);
			transaction.setStatus(Transaction.SUCCESS);
		}
	} catch (Exception e) {
		transaction.setStatus(e);
		log.error("initDataSource_error", e);
	}
}
 
Example 17
Source File: DbNodeServiceImpl.java    From pmq with Apache License 2.0 5 votes vote down vote up
private void checkMaster(DbNodeEntity dbNodeEntity) throws SQLException {
	DruidDataSource dataSource = dataSourceFactory.createDataSource();
	dataSource.setDriverClassName("com.mysql.jdbc.Driver");
	dataSource.setUsername(dbNodeEntity.getDbUserName());
	dataSource.setPassword(dbNodeEntity.getDbPass());
	dataSource.setUrl(getCon(dbNodeEntity, true));
	dataSource.setInitialSize(1);
	dataSource.setMinIdle(0);
	dataSource.setMaxActive(1);
	dataSource.init();
	dataSource = null;
}
 
Example 18
Source File: BaseMatrixTestCase.java    From tddl5 with Apache License 2.0 4 votes vote down vote up
public static DataSource JDBCClient(String dbTypeStack, boolean async) throws Exception {
    if (dbTypeStack.equals("tddl") || dbTypeStack.equals("mysql")) {
        TDataSource tddlDatasource = null;
        tddlDatasource = new TDataSource();
        tddlDatasource.setAppName("andor_mysql_qatest");
        tddlDatasource.setRuleFile(ruleFile + dbTypeStack + "_" + rule);
        tddlDatasource.setTopologyFile(machineTapologyFile);
        tddlDatasource.setSchemaFile(schemaFile + dbTypeStack + "_" + schema);
        tddlDatasource.setSequenceFile(schemaFile + dbTypeStack + "_" + sequence);
        // tddlDatasource.setConfigMode("mock");

        Map<String, Object> cp = new HashMap<String, Object>();

        if ("hbase".equalsIgnoreCase(dbTypeStack)) {
            cp.put(ConnectionProperties.HBASE_MAPPING_FILE, "matrix/hbase_mapping.xml");
        }

        tddlDatasource.setConnectionProperties(cp);
        try {
            tddlDatasource.init();
        } catch (Exception e) {
            Assert.fail(ExceptionUtils.getFullStackTrace(e));
        }

        return tddlDatasource;
    } else if (dbTypeStack.equals("tddl-server")) {
        cobarServer = CobarServer.getInstance();
        cobarServer.init();

        DruidDataSource druidDs = new DruidDataSource();
        String url = "jdbc:mysql://127.0.0.1:8607/andor_mysql_qatest";
        String user = "andor_mysql_qatest";
        String passWord = "123456";

        druidDs.setUrl(url);
        druidDs.setUsername(user);
        druidDs.setPassword(passWord);
        druidDs.init();
        return druidDs;
    }

    throw new IllegalAccessError();
}
 
Example 19
Source File: DBTest.java    From canal-1.1.3 with Apache License 2.0 4 votes vote down vote up
@Test
public void test01() throws SQLException {
    DruidDataSource dataSource = new DruidDataSource();
    // dataSource.setDriverClassName("oracle.jdbc.OracleDriver");
    // dataSource.setUrl("jdbc:oracle:thin:@127.0.0.1:49161:XE");
    // dataSource.setUsername("mytest");
    // dataSource.setPassword("m121212");

    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/mytest?useUnicode=true");
    dataSource.setUsername("root");
    dataSource.setPassword("121212");

    dataSource.setInitialSize(1);
    dataSource.setMinIdle(1);
    dataSource.setMaxActive(2);
    dataSource.setMaxWait(60000);
    dataSource.setTimeBetweenEvictionRunsMillis(60000);
    dataSource.setMinEvictableIdleTimeMillis(300000);

    dataSource.init();

    Connection conn = dataSource.getConnection();

    conn.setAutoCommit(false);
    PreparedStatement pstmt = conn
        .prepareStatement("insert into user (id,name,role_id,c_time,test1,test2) values (?,?,?,?,?,?)");

    java.util.Date now = new java.util.Date();
    for (int i = 1; i <= 10000; i++) {
        pstmt.clearParameters();
        pstmt.setLong(1, (long) i);
        pstmt.setString(2, "test_" + i);
        pstmt.setLong(3, (long) i % 4 + 1);
        pstmt.setDate(4, new java.sql.Date(now.getTime()));
        pstmt.setString(5, null);
        pstmt.setBytes(6, null);

        pstmt.execute();
        if (i % 5000 == 0) {
            conn.commit();
        }
    }
    conn.commit();

    pstmt.close();

    // Statement stmt = conn.createStatement();
    // ResultSet rs = stmt.executeQuery("select * from user t where 1=2");
    //
    // ResultSetMetaData rsm = rs.getMetaData();
    // int cnt = rsm.getColumnCount();
    // for (int i = 1; i <= cnt; i++) {
    // System.out.println(rsm.getColumnName(i) + " " + rsm.getColumnType(i));
    // }

    // rs.close();
    // stmt.close();

    // PreparedStatement pstmt = conn
    // .prepareStatement("insert into tb_user (id,name,role_id,c_time,test1,test2)
    // values (?,?,?,?,?,?)");
    // pstmt.setBigDecimal(1, new BigDecimal("5"));
    // pstmt.setString(2, "test");
    // pstmt.setBigDecimal(3, new BigDecimal("1"));
    // pstmt.setDate(4, new Date(new java.util.Date().getTime()));
    // byte[] a = { (byte) 1, (byte) 2 };
    // pstmt.setBytes(5, a);
    // pstmt.setBytes(6, a);
    // pstmt.execute();
    //
    // pstmt.close();

    conn.close();
    dataSource.close();
}
 
Example 20
Source File: TAtomDsConfHandle.java    From tddl5 with Apache License 2.0 4 votes vote down vote up
/**
 * 初始化方法,创建对应的数据源,只能被调用一次
 * 
 * @throws Exception
 */
@Override
public void doInit() throws TddlException {
    // 1.初始化参数检查
    if (TStringUtil.isBlank(this.appName) || TStringUtil.isBlank(this.dbKey)) {
        throw new TddlException(ErrorCode.ERR_CONFIG_MISS_ATOM_CONFIG, this.dbKey, "appName or dbKey");
    }
    // 2.配置dbConfManager
    AtomConfigManager defaultDbConfManager = new AtomConfigManager();
    defaultDbConfManager.setGlobalConfigDataId(TAtomConstants.getGlobalDataId(this.dbKey));
    defaultDbConfManager.setAppConfigDataId(TAtomConstants.getAppDataId(this.appName, this.dbKey));
    defaultDbConfManager.setUnitName(unitName);
    // 初始化dbConfManager
    defaultDbConfManager.init(appName);
    dbConfManager = defaultDbConfManager;
    // 3.获取全局配置
    String globaConfStr = dbConfManager.getGlobalDbConf();
    // 注册全局配置监听
    registerGlobaDbConfListener(defaultDbConfManager);
    if (TStringUtil.isBlank(globaConfStr)) {
        throw new TddlException(ErrorCode.ERR_CONFIG_MISS_ATOM_CONFIG, this.dbKey, "globalConfig");
    }
    // 4.获取应用配置
    String appConfStr = dbConfManager.getAppDbDbConf();
    // 注册应用配置监听
    registerAppDbConfListener(defaultDbConfManager);
    if (TStringUtil.isBlank(appConfStr)) {
        throw new TddlException(ErrorCode.ERR_CONFIG_MISS_ATOM_CONFIG, this.dbKey, "appConfig");
    }
    lock.lock();
    try {
        // 5.解析配置string成TAtomDsConfDO
        runTimeConf = TAtomConfParser.parserTAtomDsConfDO(globaConfStr, appConfStr);
        // 6.处理本地优先配置
        overConfByLocal(localConf, runTimeConf);
        // 7.如果没有设置本地密码,则用订的密码,初始化passwdManager
        if (TStringUtil.isBlank(this.runTimeConf.getPasswd())) {
            // 检查dbKey和对应的userName是否为空
            if (TStringUtil.isBlank(runTimeConf.getUserName())) {
                throw new TddlException(ErrorCode.ERR_CONFIG_MISS_ATOM_CONFIG, this.dbKey, "userName");
            }
            AtomPasswdManager diamondDbPasswdManager = new AtomPasswdManager();
            diamondDbPasswdManager.setPasswdConfDataId(TAtomConstants.getPasswdDataId(runTimeConf.getDbName(),
                runTimeConf.getDbType(),
                runTimeConf.getUserName()));
            diamondDbPasswdManager.setUnitName(unitName);
            diamondDbPasswdManager.init(appName);
            dbPasswdManager = diamondDbPasswdManager;
            // 获取密码
            String passwd = dbPasswdManager.getPasswd();
            registerPasswdConfListener(diamondDbPasswdManager);
            if (TStringUtil.isBlank(passwd)) {
                throw new TddlException(ErrorCode.ERR_CONFIG_MISS_PASSWD, this.dbKey);
            }
            runTimeConf.setPasswd(passwd);
        }
        // 8.转换tAtomDsConfDO
        DruidDataSource druidDataSource = convertTAtomDsConf2DruidConf(TAtomDsConfHandle.this.dbKey,
            this.runTimeConf,
            TAtomConstants.getDbNameStr(this.unitName, this.appName, this.dbKey));
        // 9.参数检查如果参数不正确直接抛出异常
        if (!checkLocalTxDataSourceDO(druidDataSource)) {
            String errorMsg = "[ConfigError]init dataSource Prams Error! config is : " + druidDataSource.toString();
            logger.error(errorMsg);
            throw new TddlException(ErrorCode.ERR_CONFIG, errorMsg);
        }
        // 10.创建数据源
        // druidDataSource.setUseJmx(false);
        // LocalTxDataSource localTxDataSource = TaobaoDataSourceFactory
        // .createLocalTxDataSource(localTxDataSourceDO);
        // 11.将创建好的数据源是指到TAtomDatasource中
        try {
            druidDataSource.init();
        } catch (SQLException e) {
            throw new TddlNestableRuntimeException(e);
        }

        // druidDataSource.getDataSourceStat().setMaxSqlSize(DruidDsConfHandle.druidStatMaxKeySize);
        this.druidDataSource = druidDataSource;
        clearDataSourceWrapper();
    } finally {
        lock.unlock();
    }
}