Spring aop应用之实现数据库读写分离

去年五月份的时候曾经写过一篇:Spring加Mybatis实现MySQL数据库主从读写分离,实现的原理是配置了多套数据源,相应的sqlsessionfactory,transactionmanager和事务代理各配置了一套,如果从库或数据库有多个的时候,需要配置的信息会越来越多,远远不够优雅,在我们编程界有一个规范:约定优于配置。所以就用Sping的aop实现了一个简单的数据库分离方案,具体实现代码放在了Github上,地址如下: https://github.com/bridgeli/practical-util/tree/master/src/main/java/cn/bridgeli/datasource 读者如果想使用再简单的方法就是把这个代码download下来,放到自己的项目里面,当然更优雅的方式是:打成jar包,放到项目里面了,具体打jar的方法,老夫就不在这里多说了,相信看这篇文章的读者肯定都会了。当然仅仅有这份代码,他们是不会自动生效的,既然是使用Spring的Aop实现数据库读写分离,所以肯定会有牵涉到Aop的配置了,所以在spring-mybatis.xml中有如下配置: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <!&#8211; 配置写数据源 &#8211;> <bean id="masterDataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="driverClassName" value="${bridgeli.jdbc.driver}" /> <property name="url" value="${bridgeli.jdbc.url}" /> <property name="username" value="${bridgeli.jdbc.username}" /> <property name="password" value="${bridgeli.jdbc.password}" /> <property name="validationQuery" value="${bridgeli.jdbc.validationQuery}" /> <property name="initialSize" value="1" /> <property name="maxActive" value="20" /> <property name="minIdle" value="0" /> <property name="maxWait" value="60000" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <property name="minEvictableIdleTimeMillis" value="25200000" /> <property name="removeAbandoned" value="true" /> <property name="removeAbandonedTimeout" value="1800" /> <property name="logAbandoned" value="true" /> <property name="filters" value="stat" /> </bean> <!&#8211; 配置读数据源 &#8211;> <bean id="parentSlaveDataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="driverClassName" value="${bridgeli.jdbc.driver}" /> <property name="validationQuery" value="${bridgeli.jdbc.validationQuery}" /> <property name="initialSize" value="1" /> <property name="maxActive" value="20" /> <property name="minIdle" value="0" /> <property name="maxWait" value="60000" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <property name="minEvictableIdleTimeMillis" value="25200000" /> <property name="removeAbandoned" value="true" /> <property name="removeAbandonedTimeout" value="1800" /> <property name="logAbandoned" value="true" /> <property name="filters" value="stat" /> </bean> <bean id="slaveDataSource1" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close" parent="parentSlaveDataSource"> <property name="url" value="${bridgeli_slave1.jdbc.url}" /> <property name="username" value="${bridgeli_slave1.jdbc.username}" /> <property name="password" value="${bridgeli_slave1.jdbc.password}" /> </bean> <bean id="dataSource" class="cn.bridgeli.datasource.MasterSlaveDataSource"> <property name="targetDataSources"> <map> <entry key-ref="masterDataSource" value-ref="masterDataSource"/> <entry key-ref="slaveDataSource1" value-ref="slaveDataSource1"/> </map> </property> <property name="defaultTargetDataSource" ref="masterDataSource"/> <property name="masterSlaveSelector" ref="dataSelector"/> </bean> <bean id="dataSelector" class="cn.bridgeli.datasource.MasterSlaveSelectorByPoll"> <property name="masters"> <list> <ref bean="masterDataSource"/> </list> </property> <property name="slaves"> <list> <ref bean="slaveDataSource1"/> </list> </property> <property name="defaultDataSource" ref="masterDataSource"/> </bean> <aop:aspectj-autoproxy/> <!&#8211; mybaits 数据工厂 &#8211;> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean> <!&#8211; 自动扫描所有注解的路径 &#8211;> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.bridgeli.mapper" /> <!&#8211; <property name="sqlSessionFactory" ref="sqlSessionFactory" /> &#8211;> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!&#8211; 数据库切面 &#8211;> <bean id="masterSlaveAspect" class="cn.bridgeli.datasource.MasterSlaveAspect"> <property name="prefixMasters"> <list> <value>save</value> <value>update</value> <value>delete</value> </list> </property> </bean> <aop:config> <aop:aspect id="c" ref="masterSlaveAspect"> <aop:pointcut id="tx" expression="execution(\* cn.bridgeli.service..\*.*(..))"/> <aop:before pointcut-ref="tx" method="before"/> </aop:aspect> </aop:config> <context:annotation-config /> <context:component-scan base-package="cn.bridgeli" /> </beans> 这样我们就很优雅的利用Spring的Aop实现了对数据库的读写分离,读的时候走slaveDataSource1这个数据源,写的时候走masterDataSource这个数据源。哎,等等,这里哪里体现了约定优于配置这一规范,他们怎么知道哪些方法走读库哪些走写库?同学你别急,仔细读读这个配置文件,你就会发现在第98行,配置了一个MasterSlaveAspect,也就是说代码里面service层(为什么是service层?)的方法以这里面配置的这些关键字打头,都将会走写库,所以当我们想让一个方法走主库的时候,必须在这个地方添加该方法的前缀或者用这里面已有的前缀,这就要求我们必须约定好走主库的方法的打头,即约定优于配置。

December 31, 2016 · 2 min · 297 words · Bridge Li

Spring加Mybatis实现MySQL数据库主从读写分离

上周在一个同事的指点下,实现了Spring加Mybatis实现了MySQL的主从读写分离,今天记一下笔记,以供自己今后参考,下面是配置文件的写法。 数据源也就是jdbc.properties,因为是主从读写分离,那么肯定有两个数据源了 jdbc.driver=org.mariadb.jdbc.Driver \# 从库,只读 slave.jdbc.url=jdbc:mariadb://xxx.xxx.xxx.xxx:3306/xxx?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&noAccessToProcedureBodies=true&autoReconnect=true slave.jdbc.username=xxx slave.jdbc.password=xxx \# 主库,需要写 master.jdbc.url=jdbc:mariadb://xxx.xxx.xxx.xxx:3306/xxx?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&noAccessToProcedureBodies=true&autoReconnect=true master.jdbc.username=xxx master.jdbc.password=xxx 这个非常简单和普通的区别不是很大,另外数据库的驱动是:mariadb,动下面就是第二个配置文件spring.xml spring.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <!&#8211; Import properties file &#8211;> <context:property-placeholder location="classpath:jdbc.properties" /> <!&#8211; Auto Scan &#8211;> <context:component-scan base-package="cn.bridgeli.demo" /> </beans> 这个文件很简单,有两个作用,①. 引入数据源配置文件;②. spring扫描的文件的路径 spring-mybatis.xml配置文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> <bean id="slaveDataSourceImpl" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driver}" /> <property name="jdbcUrl" value="${slave.jdbc.url}" /> <property name="username" value="${slave.jdbc.username}" /> <property name="password" value="${slave.jdbc.password}" /> <!&#8211; 检查数据库连接池中空闲连接的间隔时间,单位是分,默认值:240,如果要取消则设置为0 &#8211;> <property name="idleConnectionTestPeriodInMinutes" value="10" /> <!&#8211; 连接池中未使用的链接最大存活时间,单位是分,默认值:60,如果要永远存活设置为0 &#8211;> <property name="idleMaxAgeInMinutes" value="10" /> <!&#8211; 每个分区最大的连接数 &#8211;> <property name="maxConnectionsPerPartition" value="20" /> <!&#8211; 每个分区最小的连接数 &#8211;> <property name="minConnectionsPerPartition" value="10" /> <!&#8211; 分区数 ,默认值2,最小1,推荐3-4,视应用而定 &#8211;> <property name="partitionCount" value="3" /> <!&#8211; 每次去拿数据库连接的时候一次性要拿几个,默认值:2 &#8211;> <property name="acquireIncrement" value="3" /> <!&#8211; 缓存prepared statements的大小,默认值:0 &#8211;> <property name="statementsCacheSize" value="50" /> <!&#8211; 在做keep-alive的时候的SQL语句 &#8211;> <property name="connectionTestStatement" value="select 1 from dual" /> <!&#8211; 在每次到数据库取连接的时候执行的SQL语句,只执行一次 &#8211;> <property name="initSQL" value="select 1 from dual" /> <property name="closeConnectionWatch" value="false" /> <property name="logStatementsEnabled" value="true" /> <property name="transactionRecoveryEnabled" value="true" /> </bean> <bean id="masterDataSourceImpl" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driver}" /> <property name="jdbcUrl" value="${master.jdbc.url}" /> <property name="username" value="${master.jdbc.username}" /> <property name="password" value="${master.jdbc.password}" /> <!&#8211; 检查数据库连接池中空闲连接的间隔时间,单位是分,默认值:240,如果要取消则设置为0 &#8211;> <property name="idleConnectionTestPeriodInMinutes" value="10" /> <!&#8211; 连接池中未使用的链接最大存活时间,单位是分,默认值:60,如果要永远存活设置为0 &#8211;> <property name="idleMaxAgeInMinutes" value="10" /> <!&#8211; 每个分区最大的连接数 &#8211;> <property name="maxConnectionsPerPartition" value="20" /> <!&#8211; 每个分区最小的连接数 &#8211;> <property name="minConnectionsPerPartition" value="10" /> <!&#8211; 分区数 ,默认值2,最小1,推荐3-4,视应用而定 &#8211;> <property name="partitionCount" value="3" /> <!&#8211; 每次去拿数据库连接的时候一次性要拿几个,默认值:2 &#8211;> <property name="acquireIncrement" value="3" /> <!&#8211; 缓存prepared statements的大小,默认值:0 &#8211;> <property name="statementsCacheSize" value="50" /> <!&#8211; 在做keep-alive的时候的SQL语句 &#8211;> <property name="connectionTestStatement" value="select 1 from dual" /> <!&#8211; 在每次到数据库取连接的时候执行的SQL语句,只执行一次 &#8211;> <property name="initSQL" value="select 1 from dual" /> <property name="closeConnectionWatch" value="false" /> <property name="logStatementsEnabled" value="true" /> <property name="transactionRecoveryEnabled" value="true" /> </bean> <!&#8211; DataSource/Master &#8211;> <bean id="masterDataSource" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy"> <property name="targetDataSource" ref="masterDataSourceImpl" /> </bean> <bean id="masterTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="masterDataSource" /> </bean> <bean id="masterTransactionTemplate" class="org.springframework.transaction.support.TransactionTemplate"> <property name="transactionManager" ref="masterTransactionManager" /> </bean> <!&#8211; DataSource/Slave &#8211;> <bean id="slaveDataSource" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy"> <property name="targetDataSource" ref="slaveDataSourceImpl" /> </bean> <bean id="slaveTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="slaveDataSource" /> </bean> <bean id="slaveTransactionTemplate" class="org.springframework.transaction.support.TransactionTemplate"> <property name="transactionManager" ref="slaveTransactionManager" /> </bean> <!&#8211; Mybatis/Master &#8211;> <bean id="masterSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="masterDataSource"></property> <property name="configLocation" value="classpath:mybatis.xml" /> <property name="typeAliasesPackage" value="cn.bridgeli.demo.entity" /> <property name="mapperLocations"> <list> <value>classpath:cn/bridgeli/demo/mapper/master/*.xml</value> </list> </property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.bridgeli.demo.mapper.master" /> <property name="sqlSessionFactoryBeanName" value="masterSqlSessionFactory" /> </bean> <!&#8211; Mybatis/Slave &#8211;> <bean id="slaveSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="slaveDataSource"></property> <property name="configLocation" value="classpath:mybatis.xml" /> <property name="typeAliasesPackage" value="cn.bridgeli.demo.entity" /> <property name="mapperLocations"> <list> <value>classpath:cn/bridgeli/demo/mapper/slave/*.xml</value> </list> </property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.bridgeli.demo.mapper.slave" /> <property name="sqlSessionFactoryBeanName" value="slaveSqlSessionFactory" /> </bean> <!&#8211; Configuration transaction advice &#8211;> <tx:advice id="txAdvice" transaction-manager="masterTransactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="get*" read-only="true" propagation="SUPPORTS" /> <tx:method name="list*" read-only="true" propagation="SUPPORTS" /> </tx:attributes> </tx:advice> <!&#8211; Configuration transaction aspect &#8211;> <aop:config> <aop:pointcut id="systemServicePointcut" expression="execution(\* cn.bridgeli.demo.service.\*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="systemServicePointcut" /> </aop:config> </beans> 这个配置文件老夫是完整的copy了下来,看起来也比较易懂,就不做解释了,需要说明的mybatis下那些dao的接口,分别对应cn.bridgeli.demo.mapper.master、cn.bridgeli.demo.mapper.slave,cn.bridgeli.demo.mapper.master下的这些dao接口是要写的,另一个是读的,这些接口对应的配置文件肯定就是他们对应的文件夹下面的xml文件了,在将来的项目中几乎可以照抄 ...

May 3, 2015 · 3 min · 502 words · Bridge Li