实现方式
db.properties
jdbc.write.driver=com.mysql.jdbc.Driverjdbc.write.url=jdbc:mysql://192.168.142.128:3306/mysql_demojdbc.write.username=rootjdbc.write.password=leonjdbc.read.driver=com.mysql.jdbc.Driverjdbc.read.url=jdbc:mysql://192.168.142.129:3306/mysql_demojdbc.read.username=rootjdbc.read.password=itcast
applicationContext-datasource.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:aop="/schema/aop"xmlns:tx="/schema/tx"xmlns:context="/schema/context"xsi:schemaLocation="/schema/beans /schema/beans/spring-beans.xsd/schema/tx /schema/tx/spring-tx.xsd/schema/aop /schema/aop/spring-aop.xsd/schema/context /schema/context/spring-context.xsd"><!-- 配置数据源 - Read --><bean id="readDataSource" class="com.mchange.boPooledDataSource" destroy-method="close" lazy-init="true"><property name="driverClass" value="${jdbc.read.driver}"></property><property name="jdbcUrl" value="${jdbc.read.url}"></property><property name="user" value="${jdbc.read.username}"></property><property name="password" value="${jdbc.read.password}"></property></bean><!-- 配置数据源 - Write --><bean id="writeDataSource" class="com.mchange.boPooledDataSource" destroy-method="close" lazy-init="true"><property name="driverClass" value="${jdbc.write.driver}"></property><property name="jdbcUrl" value="${jdbc.write.url}"></property><property name="user" value="${jdbc.write.username}"></property><property name="password" value="${jdbc.write.password}"></property></bean><!-- 配置动态分配的读写 数据源 --><bean id="dataSource" class="cn.leon.aop.datasource.ChooseDataSource" lazy-init="true"><property name="targetDataSources"><map key-type="java.lang.String" value-type="javax.sql.DataSource"><entry key="write" value-ref="writeDataSource"/><entry key="read" value-ref="readDataSource"/></map></property><property name="defaultTargetDataSource" ref="writeDataSource"/><property name="methodType"><map key-type="java.lang.String"><entry key="read" value=",get,select,count,list,query,find"/><entry key="write" value=",add,create,update,delete,remove,insert"/></map></property></bean></beans>
ChooseDataSource
public class ChooseDataSource extends AbstractRoutingDataSource {public static Map<String, List<String>> METHOD_TYPE_MAP = new HashMap<String, List<String>>();/*** 实现父类中的抽象方法,获取数据源名称* @return*/protected Object determineCurrentLookupKey() {return DataSourceHandler.getDataSource();}// 设置方法名前缀对应的数据源public void setMethodType(Map<String, String> map) {for (String key : map.keySet()) {List<String> v = new ArrayList<String>();String[] types = map.get(key).split(",");for (String type : types) {if (!StringUtils.isEmpty(type)) {v.add(type);}}METHOD_TYPE_MAP.put(key, v);}System.out.println("METHOD_TYPE_MAP : "+METHOD_TYPE_MAP);}}
如果觉得《MySQL高级 - 案例 - 系统性能优化 - 数据源配置》对你有帮助,请点赞、收藏,并留下你的观点哦!