Netkiller Spring Cloud 手札
Spring Cloud Cookbook
Mr. Neo Chan, 陈景峯(BG7NYT)
中国广东省深圳市望海路半岛城邦三期 518067 +86 13113668890<>
MMDVM Hotspot:
YSF80337 - CN China 1 - W24166/TG46001 BM_China_46001 - DMR Radio ID 4600441$Id: book.xml 606 2013-05-29 09:52:58Z netkiller $
版权 © 2015-2019 Neo Chan
版权声明
转载请与作者联系,转载时请务必标明文章原始出处和作者信息及本声明。
| | |
|
5.19.1. Master / Slave 主从数据库数据源配置
5.19.1.1. application.properties
spring.datasource.master.driverClassName = com.mysql.cj.jdbc.Driverspring.datasource.master.url=jdbc:mysql://192.168.1.240:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=falsespring.datasource.master.username = rootspring.datasource.master.password = passwordspring.datasource.slave.driverClassName = com.mysql.cj.jdbc.Driverspring.datasource.slave.url=jdbc:mysql://192.168.1.250:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=falsespring.datasource.slave.username = rootspring.datasource.slave.password = passwordspring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
5.19.1.2. 配置主从数据源
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;@Configurationpublic 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); }}
5.19.1.3. 选择数据源
// 默认是 Master @Autowired private JdbcTemplate jdbcTemplate; // 或者这样写 @Qualifier("masterJdbcTemplate") @Autowired private JdbcTemplate masterJdbcTemplate; // 下面是 Slave 数据源 @Qualifier("slaveJdbcTemplate") @Autowired private JdbcTemplate slaveJdbcTemplate;