ssm maven spring AOP读写分离

总体流程

配置最开始写在pom.xml文件,解析到数据库配置文件,再解析到spring配置文件。

自定义注解DataSource;通过这个注解并且在spring、springmv配置文件添加AOP拦截,去定义拦截函数,根据参数切换数据源。

即通过注解实现AOP拦截controller,或者service层。从而实现读写分离。

具体见代码和注释。

1,pom.xml 配置数据库部分
<profile>
<id>local</id>
<properties>
<db-url><![CDATA[jdbc:mysql://XXX?autoReconnect=true&autoReconnectForPools=true&useUnicode=true&characterEncoding=utf8]]></db-url>
<db-driverClassName>com.mysql.jdbc.Driver</db-driverClassName>
<db-username>XXX</db-username>
<db-password>XXX</db-password> <aliyun.oss.endpoint><![CDATA[oss-cn-beijing.aliyuncs.com]]></aliyun.oss.endpoint>
<aliyun_oss_endpointURL><![CDATA[http://oss-cn-beijing.aliyuncs.com]]></aliyun_oss_endpointURL>
<aliyun.oss.accessKeyId>LTAIz0kIEQRSBc6G</aliyun.oss.accessKeyId>
<aliyun.oss.accessKeySecret>3YS3fXPvIHng11ft7wQRGDeojP2Neg</aliyun.oss.accessKeySecret>
<aliyun.oss.templateInputBucket>iceplay</aliyun.oss.templateInputBucket>
<aliyun.oss.templateResultBucket>iceplay</aliyun.oss.templateResultBucket>
<aliyun.oss.templatePicBucket>iceplay</aliyun.oss.templatePicBucket>
<aliyun.oss.picTaskInputBucket>iceplay</aliyun.oss.picTaskInputBucket>
<aliyun.oss.picTaskResultBucket>iceplay</aliyun.oss.picTaskResultBucket>
<aliyun.oss.avatorBucket>iceplay</aliyun.oss.avatorBucket>
<aliyun.oss.adviceBucket>iceplay</aliyun.oss.adviceBucket>
<aliyun.oss.fontBucket>iceplay</aliyun.oss.fontBucket>
<aliyun.oss.picimgPath>app-image</aliyun.oss.picimgPath>
<aliyun.oss.watermark></aliyun.oss.watermark> <aliyun.mq.accessKey>LTAItRByuljwgIgI</aliyun.mq.accessKey>
<aliyun.mq.secretKey>fauyIEV8LMwSj8alFYUqEXeU5VMfwY</aliyun.mq.secretKey>
<aliyun.mq.sendMsgTimeoutMillis>3000</aliyun.mq.sendMsgTimeoutMillis>
<aliyun.mq.templateTaskProducerId>PID-Template-Task</aliyun.mq.templateTaskProducerId>
<aliyun.mq.consumerId>CID-AppServer</aliyun.mq.consumerId>
<aliyun.mq.topicTemplateTask>template-tasks</aliyun.mq.topicTemplateTask>
<aliyun.mq.topicTemplateResult>template-results</aliyun.mq.topicTemplateResult>
<aliyun.mq.topicImageCreateTask>pic-tasks</aliyun.mq.topicImageCreateTask>
<aliyun.mq.topicImageCreateResult>pic-results</aliyun.mq.topicImageCreateResult>
<aliyun.mq.imageCreateTaskProducerId>PID-Pic-Task</aliyun.mq.imageCreateTaskProducerId>
<aliyun.mq.topicServerStatus>server-status</aliyun.mq.topicServerStatus>
<aliyun.mq.serverConfigProducerId>PID-Manage</aliyun.mq.serverConfigProducerId>
<aliyun.mq.topicServerConfig>server-config</aliyun.mq.topicServerConfig>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>localSalve</id>
<properties>
<dbs-url><![CDATA[jdbc:mysql://XXX?autoReconnect=true&autoReconnectForPools=true&useUnicode=true&characterEncoding=utf8]]></dbs-url>
<dbs-driverClassName>com.mysql.jdbc.Driver</dbs-driverClassName>
<dbs-username>XXX</dbs-username>
<dbs-password>XXX</dbs-password> <aliyun.oss.endpoint><![CDATA[oss-cn-beijing.aliyuncs.com]]></aliyun.oss.endpoint>
<aliyun_oss_endpointURL><![CDATA[http://oss-cn-beijing.aliyuncs.com]]></aliyun_oss_endpointURL>
<aliyun.oss.accessKeyId>LTAIz0kIEQRSBc6G</aliyun.oss.accessKeyId>
<aliyun.oss.accessKeySecret>3YS3fXPvIHng11ft7wQRGDeojP2Neg</aliyun.oss.accessKeySecret>
<aliyun.oss.templateInputBucket>iceplay</aliyun.oss.templateInputBucket>
<aliyun.oss.templateResultBucket>iceplay</aliyun.oss.templateResultBucket>
<aliyun.oss.templatePicBucket>iceplay</aliyun.oss.templatePicBucket>
<aliyun.oss.picTaskInputBucket>iceplay</aliyun.oss.picTaskInputBucket>
<aliyun.oss.picTaskResultBucket>iceplay</aliyun.oss.picTaskResultBucket>
<aliyun.oss.avatorBucket>iceplay</aliyun.oss.avatorBucket>
<aliyun.oss.adviceBucket>iceplay</aliyun.oss.adviceBucket>
<aliyun.oss.fontBucket>iceplay</aliyun.oss.fontBucket>
<aliyun.oss.picimgPath>app-image</aliyun.oss.picimgPath>
<aliyun.oss.watermark></aliyun.oss.watermark> <aliyun.mq.accessKey>LTAItRByuljwgIgI</aliyun.mq.accessKey>
<aliyun.mq.secretKey>fauyIEV8LMwSj8alFYUqEXeU5VMfwY</aliyun.mq.secretKey>
<aliyun.mq.sendMsgTimeoutMillis>3000</aliyun.mq.sendMsgTimeoutMillis>
<aliyun.mq.templateTaskProducerId>PID-Template-Task</aliyun.mq.templateTaskProducerId>
<aliyun.mq.consumerId>CID-AppServer</aliyun.mq.consumerId>
<aliyun.mq.topicTemplateTask>template-tasks</aliyun.mq.topicTemplateTask>
<aliyun.mq.topicTemplateResult>template-results</aliyun.mq.topicTemplateResult>
<aliyun.mq.topicImageCreateTask>pic-tasks</aliyun.mq.topicImageCreateTask>
<aliyun.mq.topicImageCreateResult>pic-results</aliyun.mq.topicImageCreateResult>
<aliyun.mq.imageCreateTaskProducerId>PID-Pic-Task</aliyun.mq.imageCreateTaskProducerId>
<aliyun.mq.topicServerStatus>server-status</aliyun.mq.topicServerStatus>
<aliyun.mq.serverConfigProducerId>PID-Manage</aliyun.mq.serverConfigProducerId>
<aliyun.mq.topicServerConfig>server-config</aliyun.mq.topicServerConfig>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
2,数据库配置文件(部分)
config_url:${db-url}
config_driverClassName:${db-driverClassName}
config_username:${db-username}
config_password:${db-password} salve_config_url:${dbs-url}
salve_config_driverClassName:${dbs-driverClassName}
salve_config_username:${dbs-username}
salve_config_password:${dbs-password}
3,spring springmvc配置文件

spring 配置数据连接池,数据源,拦截等。


<!-- 阿里 druid数据库连接池 -->
<bean id="dataSource_write" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<!-- 数据库基本信息配置 -->
<property name="url" value="${config_url}" />
<property name="username" value="${config_username}" />
<property name="password" value="${config_password}" />
<property name="driverClassName" value="${config_driverClassName}" />
<property name="filters" value="${filters}" />
<!-- 最大并发连接数 -->
<property name="maxActive" value="${maxActive}" />
<!-- 初始化连接数量 -->
<property name="initialSize" value="${initialSize}" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="${maxWait}" />
<!-- 最小空闲连接数 -->
<property name="minIdle" value="${minIdle}" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
<property name="validationQuery" value="${validationQuery}" />
<property name="testWhileIdle" value="${testWhileIdle}" />
<property name="testOnBorrow" value="${testOnBorrow}" />
<property name="testOnReturn" value="${testOnReturn}" />
<property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements}" />
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="${removeAbandoned}" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="${logAbandoned}" />
</bean> <!-- 阿里 druid数据库连接池 salve add by 胜杰-->
<bean id="dataSource_read_one" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<!-- 数据库基本信息配置 -->
<property name="url" value="${salve_config_url}" />
<property name="username" value="${salve_config_username}" />
<property name="password" value="${salve_config_password}" />
<property name="driverClassName" value="${salve_config_driverClassName}" />
<property name="filters" value="${filters}" />
<!-- 最大并发连接数 -->
<property name="maxActive" value="${maxActive}" />
<!-- 初始化连接数量 -->
<property name="initialSize" value="${initialSize}" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="${maxWait}" />
<!-- 最小空闲连接数 -->
<property name="minIdle" value="${minIdle}" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
<property name="validationQuery" value="${validationQuery}" />
<property name="testWhileIdle" value="${testWhileIdle}" />
<property name="testOnBorrow" value="${testOnBorrow}" />
<property name="testOnReturn" value="${testOnReturn}" />
<property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements}" />
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="${removeAbandoned}" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="${logAbandoned}" />
</bean>
<!-- 配置动态数据源,并设置默认的数据源。如果想要在类上加注解,则要去掉这个默认的数据源。 -->
<bean id="dataSource" class="com.fh.dataexchanger.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<!-- write -->
<entry key="write" value-ref="dataSource_write"/>
<!-- read -->
<entry key="read" value-ref="dataSource_read_one"/>
</map> </property>
<property name="defaultTargetDataSource" ref="dataSource_write"/>
</bean>
<!--第一个 * —— 通配 任意返回值类型
第二三个 * —— 通配 包com.(任意).service下的任意class
第四个 * —— 通配 包com.evan.crm.service下的任意class的任意方法
第四个 .. —— 通配 方法可以有0个或多个参数 -->
<aop:aspectj-autoproxy proxy-target-class="true" />
<bean id="dataSourceAspect" class="com.fh.dataexchanger.DataSourceAspect" />
<aop:config>
<aop:aspect id="c" ref="dataSourceAspect">
<aop:pointcut id="tx"
expression="execution(* com.*.controller..*.*(..))" />
<aop:before pointcut-ref="tx" method="before" />
</aop:aspect>
</aop:config>

spring mvc:加这一句主要是为了使之可以拦截controller


<!-- 启动对@AspectJ注解的支持 -->
<aop:aspectj-autoproxy />

加上边一句的同时头部要加上下边三句到相应的位置。

xmlns:aop="http://www.springframework.org/schema/aop"  

    http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd

4,java 数据源文件

定义一个名为DataSource的注解,Target用于指定注解可以添加的位置。两个参数的意思是:类和接口、方法。Retention 的作用时指定注解运行时间,运行时。


@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSource { String value();
}

定义AOP切面以便拦截所有带有注解@DataSource的方法,取出注解的值作为数据源标识放到DynamicDataSourceHolder的线程变量中

public class DataSourceAspect {

   public void before(JoinPoint point){
Object target = point.getTarget();
String method = point.getSignature().getName();
System.out.println(method);
Class<?> classz = target.getClass();
Class<?>[] parameterTypes = ((MethodSignature) point.getSignature())
.getMethod().getParameterTypes(); try {
Method m = classz.getDeclaredMethod(method, parameterTypes);
if(m != null && m.isAnnotationPresent(DataSource.class)){
DataSource ds = m.getAnnotation(DataSource.class);
DynamicDataSourceHolder.putDataSource(ds.value());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Spring 的AbstractRoutingDataSource获取数据源之前会先调用determineCurrentLookupKey方法查找当前的lookupKey,这个lookupKey就是数据源标识。

因此通过重写这个查找数据源标识的方法就可以让spring切换到指定的数据源了。

创建一个DynamicDataSource的类,继承AbstractRoutingDataSource并重写determineCurrentLookupKey方法,

public class DynamicDataSource extends AbstractRoutingDataSource{

	@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceHolder.getDataSource();
} }

创建DynamicDataSourceHolder用于持有和设置当前线程中使用的数据源标识

public class DynamicDataSourceHolder {

	public static final ThreadLocal<String> holder = new ThreadLocal<String>();

	public static void putDataSource(String name){
holder.set(name);
} public static String getDataSource(){
return holder.get();
}
}

参考:http://www.cnblogs.com/liujiduo/p/5004691.html

http://blog.csdn.net/u010004317/article/details/47700447

http://blog.csdn.net/mfc2003/article/details/48490151

----名白

转载注明出处:http://www.cnblogs.com/mingbai/p/writeread.html

ssm maven spring AOP读写分离的更多相关文章

  1. Spring aop读写分离

    一.采用读写分离技术的目标 随着网站的业务不断扩展,数据不断增加,用户越来越多,数据库的压力也就越来越大,采用传统的方式,比如:数据库或者SQL的优化基本已达不到要求,这个时候可以采用读写分离的策略来 ...

  2. java 使用spring实现读写分离

    最近上线的项目中数据库数据已经临近饱和,最大的一张表数据已经接近3000W,百万数据的表也有几张,项目要求读数据(select)时间不能超过0.05秒,但实际情况已经不符合要求,explain建立索引 ...

  3. spring实现读写分离

    (转自:http://www.cnblogs.com/surge/p/3582248.html) 现在大型的电子商务系统,在数据库层面大都采用读写分离技术,就是一个Master数据库,多个Slave数 ...

  4. 使用Spring实现读写分离( MySQL实现主从复制)

    详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt403 1.  背景 我们一般应用对数据库而言都是"读多写少&quo ...

  5. Spring 数据库读写分离

    读写分离常见有俩种方式 1 第一种方式比较常用就是定义2个数据库连接,一个是Master,另一个是Slave.更新数据时我们取Master,查询数据时取Slave.太过简单不做介绍. 2 第二种方数据 ...

  6. Spring + Mybatis 读写分离

    项目背景:项目开发中数据库使用了读写分离,所有查询语句走从库,除此之外走主库. 实现思路是: 第一步,实现动态切换数据源:配置两个DataSource,配置两个SqlSessionFactory指向两 ...

  7. 使用Spring实现读写分离( MySQL实现主从复制)(转)

    本文转自:http://blog.csdn.net/jack85986370/article/details/51559232 1.  背景 我们一般应用对数据库而言都是“读多写少”,也就说对数据库读 ...

  8. 002-使用Spring实现读写分离(MySQL实现主从复制)

    一. 背景 一般应用对数据库而言都是“读多写少”,也就说对数据库读取数据的压力比较大主库,负责写入数据,我们称之为:写库:从库,负责读取数据,我们称之为:读库: 1. 读库和写库的数据一致:2. 写数 ...

  9. [转]Spring数据库读写分离

    数据库的读写分离简单的说是把对数据库的读和写操作分开对应不同的数据库服务器,这样能有效地减轻数据库压力,也能减轻io压力. 主(master)数据库提供写操作,从(slave)数据库提供读操作,其实在 ...

随机推荐

  1. 对Java中堆栈的解析

    Java把内存分为两种:一种是栈内存,一种是堆内存 栈内存:在函数中定义的一些基本类型的变量和对象的引用变量,当超过变量的作用域之后,Java自动释放该变量内存 堆内存:存放new创建的对象和数组,由 ...

  2. python爬虫小结1

    先看正则化,正则化就是描述命令和字符切分.查找.筛选等功能的方便方式. http://www.cnblogs.com/fnng/archive/2013/05/20/3089816.html 一个游戏 ...

  3. 解决IOS iframe不滚动问题

    .frameBox{ position: fixed; top: 0; left: 0; right: 0; bottom: 0; -webkit-overflow-scrolling: touch; ...

  4. 用VS2015写一个简单的ASP.net网站

    第一步:打开VS2015,然后新建一个空的解决方案,其中解决方案的名称WebSiteTest可类似认为是本次网站的名称,系统会以该名称(WebSiteTest)生成一个文件夹,在WebSites文件夹 ...

  5. 强推一款开源集成开发环境——Geany

    本人是一个标标准准的程序员,集成开发环境在电脑上大概看一下有:Code Blocks(C/C++),VS(C#,C/C++),eclipse(Java),Hbuild和web storm(前端),py ...

  6. 从一个word文件中读取所有的表格和标题(1)

    首先讲需求: 从word文件中读表格里的数据,然后插入数据库中.word文件中的表格是带有标题的,把标题读出来,进行匹配数据库. 需求分析: word2007底层是以xml文件存储的,所以分析xml的 ...

  7. 关于java字节流的read()方法返回值为int的思考

    我们都知道java中io操作分为字节流和字符流,对于字节流,顾名思义是按字节的方式读取数据,所以我们常用字节流来读取二进制流(如图片,音乐 等文件).问题是为什么字节流中定义的read()方法返回值为 ...

  8. 使用performance monitor 查看 每一个cpu core的cpu time

    使用performance monitor 查看 每一个cpu core的cpu time: 打开performance monitor,添加 counter 如下 运行一段cpu bound 的代码 ...

  9. 为什么树莓派不会受到 Spectre 和 Meltdown 攻击

    最近爆出来的 Intel CPU 的底层漏洞可谓是影响巨大,过去20年的电脑都可能会受影响.前几天 Raspberry Pi 的官方 Twitter(@Raspberry_Pi) 转推了这篇文章,通过 ...

  10. Nginx中并发性能相关配置参数说明

    worker_processes:开启worker进程的数目,通常可设置为CPU核心的倍数.在不清楚的情况下,可设置成一倍于CPU核心数或auto(Nginx将自动发现CPU核心数). worker_ ...