目前有個需求,須要使用不一樣的數據源,例如某業務要用A數據源,另外一個業務要用B數據源。css
<!-- 阿里的druid 依賴log4j -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 引入mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
二、application.properties配置文件html
#主數據庫 master: db: driverClassName: com.mysql.jdbc.Driver url: jdbc:mysql://47.111.22.159:3306/xinyar_erp_uat?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false username: erp_test password: erp_test@abc #從數據庫 slave: db: driverClassName: com.mysql.jdbc.Driver url: jdbc:mysql://47.111.22.159:3306/erp-test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false username: erp_test password: erp_test@abc mybatis: mapper-locations: classpath*:com/xinyartech/erp/*/xml/*/*.xml type-aliases-package: com.xinyartech.erp.*.model,com.xinyartech.erp.*.vo configuration: map-underscore-to-camel-case: true
三、禁用springboot默認加載數據源配置前端
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } }
四、主數據源配置類java
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import lombok.Data; import org.springframework.beans.factory.annotation.Value; /** * 主數據源 * * @author Lynch * */ @Configuration @ConfigurationProperties(prefix = "master.db") @Data public class MasterDataSourceConfig { @Value("${master.db.url}") private String url; @Value("${master.db.username}") private String username; @Value("${master.db.password}") private String password; @Value("${master.db.driverClassName}") private String driverClassName; }
五、從數據源配置類mysql
import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import lombok.Data; /** * 從數據源 * * @author Lynch * */ @Configuration @ConfigurationProperties(prefix = "slave.db") @Data public class SlaveDataSourceConfig { @Value("${slave.db.url}") private String url; @Value("${slave.db.username}") private String username; @Value("${slave.db.password}") private String password; @Value("${slave.db.driverClassName}") private String driverClassName; }
六、數據源配置類web
import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import javax.sql.DataSource; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.Primary; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; /** * 數據源配置類 * * @author Lynch */ @Configuration public class DataSourceComponent { @Resource private MasterDataSourceConfig masterDataSourceConfig; @Resource private SlaveDataSourceConfig slaveDataSourceConfig; @Bean(name = "master") public DataSource masterDataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(masterDataSourceConfig.getUrl()); dataSource.setUsername(masterDataSourceConfig.getUsername()); dataSource.setPassword(masterDataSourceConfig.getPassword()); dataSource.setDriverClassName(masterDataSourceConfig.getDriverClassName()); return dataSource; } @Bean(name = "slave") public DataSource slaveDataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(slaveDataSourceConfig.getUrl()); dataSource.setUsername(slaveDataSourceConfig.getUsername()); dataSource.setPassword(slaveDataSourceConfig.getPassword()); dataSource.setDriverClassName(slaveDataSourceConfig.getDriverClassName()); return dataSource; } @Primary//不加這個會報錯。
@DependsOn({ "master", "slave"}) //解決數據庫循環依賴問題 @Bean(name = "multiDataSource") public MultiRouteDataSource exampleRouteDataSource() { MultiRouteDataSource multiDataSource = new MultiRouteDataSource(); Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put("master", masterDataSource()); targetDataSources.put("slave", slaveDataSource()); multiDataSource.setTargetDataSources(targetDataSources); multiDataSource.setDefaultTargetDataSource(masterDataSource()); return multiDataSource; } /** * 註冊ServletRegistrationBean * * @return
*/ @Bean public ServletRegistrationBean druidServlet() { ServletRegistrationBean reg = new ServletRegistrationBean(); reg.setServlet(new StatViewServlet()); reg.addUrlMappings("/druid/*"); reg.addInitParameter("allow", ""); // 白名單 return reg;
reg.addInitParameter("loginUsername", "duan"); reg.addInitParameter("loginPassword", "123456"); reg.addInitParameter("resetEnable", "false"); return reg; } /** * 註冊FilterRegistrationBean * * @return
*/ @Bean public FilterRegistrationBean filterRegistrationBean() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new WebStatFilter()); filterRegistrationBean.addUrlPatterns("/*"); filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); filterRegistrationBean.addInitParameter("profileEnable", "true"); filterRegistrationBean.addInitParameter("principalCookieName", "USER_COOKIE"); filterRegistrationBean.addInitParameter("principalSessionName", "USER_SESSION"); filterRegistrationBean.addInitParameter("DruidWebStatFilter", "/*"); return filterRegistrationBean; } }
七、數據源上下文spring
/** * 數據源上下文 * * @author Lynch */
public class DataSourceContext { private static final ThreadLocal<String> contextHolder = new ThreadLocal<>(); public static void setDataSource(String value) { contextHolder.set(value); } public static String getDataSource() { return contextHolder.get(); } public static void clearDataSource() { contextHolder.remove(); } }
八、DataSource路由類sql
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; import com.xinyartech.erp.config.DataSourceContext; /** * DataSource路由類 * * 重寫的函數決定了最後選擇的DataSource * * @author Lynch */
public class MultiRouteDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { // 經過綁定線程的數據源上下文實現多數據源的動態切換,有興趣的能夠去查閱資料或源碼
return DataSourceContext.getDataSource(); } }
九、修改上下文中的數據源就能夠切換本身想要使用的數據源了 數據庫
public UserVO findUser(String username) { DataSourceContext.setDataSource("slave"); UserVO userVO = userMapper.findByVO(username); System.out.println(userVO.getName()); return null; }
這種是在業務中使用代碼設置數據源的方式,也能夠使用AOP+註解的方式實現控制,還能夠前端頭部設置後端經過攔截器統一設置!後端