|
| 1 | +package io.nononi.shardingspheredemo.datasource; |
| 2 | + |
| 3 | +import org.apache.commons.dbcp2.BasicDataSource; |
| 4 | + |
| 5 | +import org.apache.shardingsphere.api.config.masterslave.MasterSlaveRuleConfiguration; |
| 6 | +import org.apache.shardingsphere.shardingjdbc.api.MasterSlaveDataSourceFactory; |
| 7 | +import org.springframework.context.annotation.Bean; |
| 8 | +import org.springframework.context.annotation.Configuration; |
| 9 | + |
| 10 | +import javax.sql.DataSource; |
| 11 | +import java.sql.SQLException; |
| 12 | +import java.util.Arrays; |
| 13 | +import java.util.HashMap; |
| 14 | +import java.util.Map; |
| 15 | +import java.util.Properties; |
| 16 | + |
| 17 | +@Configuration |
| 18 | +public class DataSourceConfig { |
| 19 | + |
| 20 | + @Bean |
| 21 | + public DataSource dataSource() throws SQLException { |
| 22 | + // Configure actual data sources |
| 23 | + Map<String, DataSource> dataSourceMap = new HashMap<>(); |
| 24 | + |
| 25 | + // Configure master data source |
| 26 | + BasicDataSource masterDataSource = new BasicDataSource(); |
| 27 | + masterDataSource.setDriverClassName("com.mysql.jdbc.Driver"); |
| 28 | + masterDataSource.setUrl("jdbc:mysql://localhost:3316/db"); |
| 29 | + masterDataSource.setUsername("root"); |
| 30 | + masterDataSource.setPassword(""); |
| 31 | + dataSourceMap.put("ds_master", masterDataSource); |
| 32 | + |
| 33 | + // Configure the first slave data source |
| 34 | + BasicDataSource slaveDataSource1 = new BasicDataSource(); |
| 35 | + slaveDataSource1.setDriverClassName("com.mysql.jdbc.Driver"); |
| 36 | + slaveDataSource1.setUrl("jdbc:mysql://localhost:3326/db"); |
| 37 | + slaveDataSource1.setUsername("root"); |
| 38 | + slaveDataSource1.setPassword(""); |
| 39 | + dataSourceMap.put("ds_slave", slaveDataSource1); |
| 40 | + |
| 41 | + |
| 42 | + // Configure read-write split rule |
| 43 | + MasterSlaveRuleConfiguration masterSlaveRuleConfig = new MasterSlaveRuleConfiguration("ds_master_slave", "ds_master", Arrays.asList("ds_slave0")); |
| 44 | + |
| 45 | + // Get data source |
| 46 | + DataSource dataSource = MasterSlaveDataSourceFactory.createDataSource(dataSourceMap, masterSlaveRuleConfig, new Properties()); |
| 47 | + return dataSource; |
| 48 | + } |
| 49 | +} |
0 commit comments