您好,登錄后才能下訂單哦!
這篇文章給大家介紹結合jdbcTemplate動態注入數據源的示例分析,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> </dependency>
CREATE TABLE `data_source` ( `id` bigint(11) NOT NULL AUTO_INCREMENT, `source_name` varchar(32) DEFAULT NULL COMMENT '數據源名稱', `source_code` varchar(12) DEFAULT NULL COMMENT '數據源編碼', `source_type` tinyint(2) DEFAULT NULL COMMENT '數據源類型(1 mysql)', `url` varchar(128) DEFAULT NULL COMMENT 'URL', `user_name` varchar(64) DEFAULT NULL COMMENT '用戶名', `password` varchar(64) DEFAULT NULL COMMENT '密碼', `state` tinyint(2) NOT NULL COMMENT '狀態(0停用 1啟用)', `create_by` varchar(20) DEFAULT NULL COMMENT '創建人', `create_time` datetime DEFAULT NULL COMMENT '創建時間', `update_by` varchar(20) DEFAULT NULL COMMENT '修改人', `update_time` datetime DEFAULT NULL COMMENT '修改時間', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COMMENT='數據源';
public class LocalCacheUtil { private static ConcurrentMap<String, DruidDataSource> cacheRepository = new ConcurrentHashMap<String, DruidDataSource>(); /** * set cache * * @param key * @param dataSource * @return */ public static boolean set(String key, DruidDataSource dataSource){ // set new cache if (key==null || key.trim().length()==0) { return false; } cacheRepository.put(key, dataSource); return true; } /** * get cache * * @param key * @return */ public static DruidDataSource get(String key){ if (key==null || key.trim().length()==0) { return null; } DruidDataSource localCacheData = cacheRepository.get(key); if (localCacheData!=null) { return localCacheData; } else { return null; } } }
@Data @TableName("data_source") public class JobDataSourceDO implements Serializable { private static final long serialVersionUID = 1L; /** * */ @TableId(value = "ID", type = IdType.AUTO) private Long id; /** * 數據源名稱 */ private String sourceName; /** * 數據源編碼 */ private String sourceCode; /** * 數據源類型(1 mysql 2 mongoDB) */ private Integer sourceType; /** * URL */ private String url; /** * 用戶名 */ private String userName; /** * 密碼 */ private String password; /** * 狀態(0停用 1啟用) */ private Integer state; /** * 創建人 */ private String createBy; /** * 創建時間 */ private Date createTime; /** * 修改人 */ private String updateBy; /** * 修改時間 */ private Date updateTime; }
public class BaseQueryTool { protected static final Logger logger = LoggerFactory.getLogger(BaseQueryTool.class); private static ConcurrentMap<String, JdbcTemplate> cacheJdbcTemplate = new ConcurrentHashMap<String, JdbcTemplate>(); private DruidDataSource druidDataSource; private JdbcTemplate jdbcTemplate; /** * @param jobDatasource */ BaseQueryTool(JobDataSourceDO jobDatasource) { logger.info("獲取數據源-------------------{}", JSON.toJSONString(jobDatasource)); try{ if (LocalCacheUtil.get(jobDatasource.getSourceName()) == null) { druidDataSource = getDataSource(jobDatasource); LocalCacheUtil.set(jobDatasource.getSourceName(),druidDataSource); } else { druidDataSource = LocalCacheUtil.get(jobDatasource.getSourceName()); } if (BaseQueryTool.cacheJdbcTemplate.get(jobDatasource.getSourceName()) == null) { JdbcTemplate jdbcTemplate = new JdbcTemplate(); jdbcTemplate.setDataSource(druidDataSource); BaseQueryTool.cacheJdbcTemplate.put(jobDatasource.getSourceName(),jdbcTemplate); this.jdbcTemplate = jdbcTemplate; } else { this.jdbcTemplate = BaseQueryTool.cacheJdbcTemplate.get(jobDatasource.getSourceName()); } logger.info("開始獲取數據源連接數-------------------,{},{}",druidDataSource.getInitialSize(),druidDataSource.getActiveCount()); }catch (Throwable e){ logger.error("獲取數據源-------------------{}",JSON.toJSONString(e)); } logger.info("獲取數據源-------------------"); } private DruidDataSource getDataSource(JobDataSourceDO jobDatasource){ DruidDataSource dataSource = new DruidDataSource (); dataSource.setUsername(jobDatasource.getUserName()); dataSource.setPassword(jobDatasource.getPassword()); dataSource.setUrl(jobDatasource.getUrl()); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); dataSource.setInitialSize(5); dataSource.setMinIdle(5); dataSource.setMaxActive(50); dataSource.setMaxWait(60000); dataSource.setTimeBetweenEvictionRunsMillis(60000); dataSource.setMinEvictableIdleTimeMillis(30000); dataSource.setValidationQuery("SELECT 1 FROM DUAL"); dataSource.setTestWhileIdle(true); dataSource.setTestOnBorrow(false); dataSource.setTestOnReturn(false); dataSource.setPoolPreparedStatements(true); return dataSource; } public JSONArray getArrByQuerySql(String querySql) { return jdbcTemplate.query(querySql,new ResultSetExtractor<JSONArray>() { @Override public JSONArray extractData(ResultSet resultSet) throws SQLException, DataAccessException { ResultSetMetaData rsd = resultSet.getMetaData(); int clength = rsd.getColumnCount(); JSONArray ja = new JSONArray(); String columnName; try { while (resultSet.next()) { JSONObject jo = new JSONObject(); for (int i = 0; i < clength; i++) { columnName = rsd.getColumnLabel(i + 1); jo.put(columnName, resultSet.getObject(i + 1)); } ja.add(jo); } } catch (Exception e) { } return ja; } }); } }
JobDataSourceDO dataSourceDO = new JobDataSourceDO(); dataSourceDO.setPassword(queryJobDefinitionByJobcode.getPassword()); dataSourceDO.setUserName(queryJobDefinitionByJobcode.getUserName()); dataSourceDO.setUrl(queryJobDefinitionByJobcode.getUrl()); dataSourceDO.setSourceType(queryJobDefinitionByJobcode.getSourceType()); dataSourceDO.setSourceName(queryJobDefinitionByJobcode.getSourceName());
JSONArray array = baseQueryTool.getArrByQuerySql(respBO.getRunSql());
關于結合jdbcTemplate動態注入數據源的示例分析就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。