中國廣東省深圳市望海路半島城邦三期
518067
+86 13113668890
<netkiller@msn.com>
java
MMDVM Hotspot:
YSF80337 - CN China 1 - W24166/TG46001
BM_China_46001 - DMR Radio ID 4600441mysql
$Id: book.xml 606 2013-05-29 09:52:58Z netkiller $git
版權 © 2015-2019 Neo Changithub
版權聲明spring
轉載請與做者聯繫,轉載時請務必標明文章原始出處和做者信息及本聲明。sql
|
|
|
|
spring.datasource.master.driverClassName = com.mysql.cj.jdbc.Driver spring.datasource.master.url=jdbc:mysql://192.168.1.240:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false spring.datasource.master.username = root spring.datasource.master.password = password spring.datasource.slave.driverClassName = com.mysql.cj.jdbc.Driver spring.datasource.slave.url=jdbc:mysql://192.168.1.250:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false spring.datasource.slave.username = root spring.datasource.slave.password = password spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
package cn.netkiller.config; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.jdbc.core.JdbcTemplate; @Configuration public class MultiDataSourceConfig { @Bean @Primary @ConfigurationProperties("spring.datasource.master") public DataSourceProperties firstDataSourceProperties() { return new DataSourceProperties(); } @Bean("Master") @Primary @ConfigurationProperties("spring.datasource.master") public DataSource firstDataSource() { return firstDataSourceProperties().initializeDataSourceBuilder().build(); } @Bean @ConfigurationProperties("spring.datasource.slave") public DataSourceProperties secondDataSourceProperties() { return new DataSourceProperties(); } @Bean(name = "Slave") @ConfigurationProperties("spring.datasource.slave") public DataSource secondDataSource() { return secondDataSourceProperties().initializeDataSourceBuilder().build(); } @Bean("masterJdbcTemplate") @Primary public JdbcTemplate primaryJdbcTemplate(@Qualifier("Master") DataSource Master) { return new JdbcTemplate(Master); } @Bean("slaveJdbcTemplate") public JdbcTemplate secondJdbcTemplate(@Qualifier("Slave") DataSource Master) { return new JdbcTemplate(Master); } }
// 默認是 Master @Autowired private JdbcTemplate jdbcTemplate; // 或者這樣寫 @Qualifier("masterJdbcTemplate") @Autowired private JdbcTemplate masterJdbcTemplate; // 下面是 Slave 數據源 @Qualifier("slaveJdbcTemplate") @Autowired private JdbcTemplate slaveJdbcTemplate;