企业如何通过vue小程序开发满足高效运营与合规性需求
1682
2023-05-21
Jdbctemplate多数据源配置方法详解
1.数据源配置
spring:
# jdbctemplate 连接多数据源配置
db1:
datasource:
jdbcurl: jdbc:mysql://127.0.0.1:3306/cloud-main1?useUnicode=true&characterEncoding=utf8&useSSL=false&allowMultiQueries=true
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
db2:
datasource:
jdbcurl: jdbc:mysql://127.0.0.1:3306/cloud-main2?useUnicode=true&characterEncoding=utf8&useSSL=false&allowMultiQueries=true
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
2.启动类
@SpringBoottuSYrfdnFwApplication(exclude = DataSourceAutoConfiguration.class)
3.config 配置datasource
package com.example.demo.jdbctemplate.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
@Configuration
public class DataSourceConfig {
@Primary //(主数据源配置)
@Bean(name = "db1")
@Qualifier("db1")
@ConfigurationProperties(prefix = "spring.db1.datasource")
public DataSource mysqlDataSource(){
return DataSourceBuilder.create().build();
}
//
@Bean(name = "db2")
@Qualifier("db2")
@ConfigurationProperties(prefix = "spring.db2.datasource")
public DataSource sqlServerDataSource(){
return DataSourceBuilder.create().build();
}
}
构造 db1JdbcTemplate、 db2JdbcTemplate
package com.example.demo.jdbctemplate.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
@Repository
public class DBLoader {
@Bean(name = "db1JdbcTemplate")
public JdbcTemplate primaryJdbcTemplate(@Qualifier("db1") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean(name = "db2JdbcTemplate")
public JdbcTemplate secondaryJdbcTemplate(@QuatuSYrfdnFwlifier("db2") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
4.调用
@Service
public class DBTools {
@Autowired
@Qualifier( "db1JdbcTemplate")
private JdbcTemplate jdbcTemplate1;
@Autowired
@Qualifier("db2JdbcTemplate")
private JdbcTemplate jdbcTemplate2 ;
JdbcTemplate jdbcTemplate;
public JdbcTemplate getDB(String db ) {
if("db1".equals(db)){
return jdbcTemplate1;
}else if ("db2".equals(db)){
return jdbcTemplate2;
}else {
return null ;
}
}
/***
* 查询
* @param sql
* @return 返回list
*/
public List
List
return queryForList;
}
}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~