数据源,对于java来说,就是可用的数据库,那么我平时开发的springboot springcloud项目,那么也就是yml或者properties中的链接信息, 例如 mysql redis influx mongodb sqlserver clickhouse nebula-graph …
一般在spring中,都已经对其做好了封装
那就不得不说下JdbcTemplate 了,只要是各种遵循了jdbc标准的数据源,也就是大部分的关系型数据库,都是可以通过它来操作的;简直就是神奇~~ 怎么使用呢?
搞一个springboot项目 由于我使用了mysql,所以还引入了mysql驱动包
org.springframework.boot spring-boot-starter-jdbc mysql mysql-connector-java runtime
然后在yml加入相应配置
spring:datasource:driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://xxxxx:3307/yuqueusername: rootpassword: 123456
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class WordApplicationTests1 {@Testvoid contextLoads() {}@AutowiredJdbcTemplate jdbcTemplate;@SneakyThrows@Testpublic void query() {List bomList = jdbcTemplate.query("select DISTINCT * from bom", new BeanPropertyRowMapper<>(Bom.class));System.out.println(JSONUtil.toJsonStr(bomList));}
}
相当于可以了,用的就是yml中的配置查询的数据库
改造后,变成了
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
class WordApplicationTests1 {@Testvoid contextLoads() {}@AutowiredJdbcTemplate jdbcTemplate;@SneakyThrows@Testpublic void query() {List bomList = jdbcTemplate.query("select DISTINCT * from bom", new BeanPropertyRowMapper<>(Bom.class));System.out.println(JSONUtil.toJsonStr(bomList));Properties properties = new Properties();properties.put("url", "jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&tinyInt1isBit=false&allowMultiQueries=true&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true");properties.put("username", "root");properties.put("driverClassName", "com.mysql.jdbc.Driver");properties.put("password", "root");DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);JdbcTemplate template = new JdbcTemplate(dataSource);List list = template.query("select * from bom", new BeanPropertyRowMapper<>(Bom.class));System.out.println(JSONUtil.toJsonStr(list));}
}
还是能用的,两个都能查询出数据
那…请小伙伴思考下,如果是用jdbc弄一个动态数据源,是不是也不是很难,我需要用哪个库的信息,就让他加载哪个库的配置信息就ok了呀.对吧?
甚至,我可以将配置信息放入数据库中,启动后,一次性加载到内存,并实例化相应的datasource 实例,然后在实例化相应的jdbctemplete,放入到的全局中,那么我就可以自如切换了!!!
若依
大体思路如下:
DynamicDataSourceContextHolder 仅仅是个缓存
DataSourceAspect 切面实现切换
DruidConfig 把所有数据源都加载进去了
重点中的重点
DynamicDataSource extends AbstractRoutingDataSource
@Overrideprotected Object determineCurrentLookupKey(){return DynamicDataSourceContextHolder.getDataSourceType();// 每次执行都会重新获取新值}
通过此次JdbcTemplate 的数据源切换,想到了之前看过的若依项目中的多数据源切换问题,这次带着我自己的想法去看,果然再次阅读,收获颇丰;算是彻底看懂了吧;
希望我的理解能为你带来启发