spring读写分离(配置多数据源)[marked]
我们今天的主角是AbstractRoutingDataSource,在Spring2.0.1发布之后,引入了AbstractRoutingDataSource,使用该类可以实现普遍意义上的多数据源管理功能。
1、扩展Spring的AbstractRoutingDataSource抽象类(该类充当了DataSource的路由中介, 能有在运行时, 根据某种key值来动态切换到真正的DataSource上。)
从AbstractRoutingDataSource的源码中:
public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean
我们可以看到,它继承了AbstractDataSource,而AbstractDataSource不就是javax.sql.DataSource的子类,So我们可以分析下它的getConnection方法:
public Connection getConnection() throws SQLException {
return determineTargetDataSource().getConnection();
}
public Connection getConnection(String username, String password) throws SQLException {
return determineTargetDataSource().getConnection(username, password);
}
获取连接的方法中,重点是determineTargetDataSource()方法,看源码:
/**
* Retrieve the current target DataSource. Determines the
* {@link #determineCurrentLookupKey() current lookup key}, performs
* a lookup in the {@link #setTargetDataSources targetDataSources} map,
* falls back to the specified
* {@link #setDefaultTargetDataSource default target DataSource} if necessary.
* @see #determineCurrentLookupKey()
*/
protected DataSource determineTargetDataSource() {
Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
Object lookupKey = determineCurrentLookupKey();
DataSource dataSource = this.resolvedDataSources.get(lookupKey);
if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
dataSource = this.resolvedDefaultDataSource;
}
if (dataSource == null) {
throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
}
return dataSource;
}
上面这段源码的重点在于determineCurrentLookupKey()方法,这是AbstractRoutingDataSource类中的一个抽象方法,而它的返回值是你所要用的数据源dataSource的key值,有了这个key值,resolvedDataSource(这是个map,由配置文件中设置好后存入的)就从中取出对应的DataSource,如果找不到,就用配置默认的数据源。
看完源码,应该有点启发了吧,没错!你要扩展AbstractRoutingDataSource类,并重写其中的determineCurrentLookupKey()方法,来实现数据源的切换:
public class DynamicDataSource extends AbstractRoutingDataSource{
@Override
protected Object determineCurrentLookupKey() {
return DBContextHolder.getDBType();
}
}
DataSourceHolder这个类则是我们自己封装的对数据源进行操作的类:
public class DataSourceHolder {
//线程本地环境
private static final ThreadLocal<String> dataSources = new ThreadLocal<String>();
//设置数据源
public static void setDataSource(String customerType) {
dataSources.set(customerType);
} //获取数据源
public static String getDataSource() {
return (String) dataSources.get();
} //清除数据源
public static void clearDataSource() {
dataSources.remove();
}
}
setDataSource如何使用呢?我们可以在程序里面自己写:
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
BaseDAO dao = (BaseDAO) context.getBean("sqlBaseDAO", BaseDAOImpl.class);
try {
DataSourceHolder.setDataSource("data1");
System.err.println(dao.select("select count(*) sum from TEST t ").get(0).get("SUM"));
DataSourceHolder.setDataSource("data2");
System.err.println(dao.select("select count(*) sum from TEST t ").get(0).get("SUM"));
} catch (Exception e) {
e.printStackTrace();
} finally{
DataSourceHolder.clearDataSource();
}
也可以用更优雅的方式aop,把配置的数据源类型都设置成为注解标签,在service层中需要切换数据源的方法上,写上注解标签,调用相应方法切换数据源:
@DataSource(name=DataSource.slave1)
public List getProducts(){
}
import java.lang.annotation.*;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documentedpublic @interface DataSource {
String name() default DataSource.master;
public static String master = "dataSource1";
public static String slave1 = "dataSource2";
public static String slave2 = "dataSource3";
}
有时候我们可能要实现的功能是读写分离,要求select走一个库,update,delete走一个库,我们有了规则就不想每个方法都去写注解了
我们先把spring配置文件搞上:
<bean id = "dataSource1" class = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource">
<property name="url" value="${db1.url}"/>
<property name = "user" value = "${db1.user}"/>
<property name = "password" value = "${db1.pwd}"/>
<property name="autoReconnect" value="true"/>
<property name="useUnicode" value="true"/>
<property name="characterEncoding" value="UTF-8"/>
</bean> <bean id = "dataSource2" class = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource">
<property name="url" value="${db2.url}"/>
<property name = "user" value = "${db2.user}"/>
<property name = "password" value = "${db2.pwd}"/>
<property name="autoReconnect" value="true"/>
<property name="useUnicode" value="true"/>
<property name="characterEncoding" value="UTF-8"/>
</bean> <bean id = "dataSource3" class = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource">
<property name="url" value="${db3.url}"/>
<property name = "user" value = "${db3.user}"/>
<property name = "password" value = "${db3.pwd}"/>
<property name="autoReconnect" value="true"/>
<property name="useUnicode" value="true"/>
<property name="characterEncoding" value="UTF-8"/>
</bean>
<!-- 配置多数据源映射关系 -->
<bean id="dataSource" class="com.datasource.test.util.database.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="dataSource1" value-ref="dataSource1"></entry>
<entry key="dataSource2" value-ref="dataSource2"></entry>
<entry key="dataSource3" value-ref="dataSource3"></entry>
</map>
</property>
<!-- 默认目标数据源为你主库数据源 -->
<property name="defaultTargetDataSource" ref="dataSource1"/>
</bean>
<!-- JdbcTemplate使用动态数据源的配置 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<ref bean="dynamicDataSource" />
</property>
</bean>
接着我们还是接着上面的aop在一定规则下的配置
<aop:config expose-proxy="true">
<aop:pointcut id="txPointcut" expression="execution(* com.jwdstef..service.impl..*.*(..))" />
<aop:aspect ref="readWriteInterceptor" order="1">
<aop:around pointcut-ref="txPointcut" method="readOrWriteDB"/>
</aop:aspect>
</aop:config> <bean id="readWriteInterceptor" class="com.test.ReadWriteInterceptor">
<property name="readMethodList">
<list>
<value>query*</value>
<value>use*</value>
<value>get*</value>
<value>count*</value>
<value>find*</value>
<value>list*</value>
<value>search*</value>
</list>
</property> <property name="writeMethodList">
<list>
<value>save*</value>
<value>add*</value>
<value>create*</value>
<value>insert*</value>
<value>update*</value>
<value>merge*</value>
<value>del*</value>
<value>remove*</value>
<value>put*</value>
<value>write*</value>
</list>
</property>
</bean>
配置的切面类是ReadWriteInterceptor。这样当Mapper接口的方法被调用时,会先调用这个切面类的readOrWriteDB方法。在这里需要注意<aop:aspect>中的order="1" 配置,主要是为了解决切面于切面之间的优先级问题,因为整个系统中不太可能只有一个切面类。
public class ReadWriteInterceptor {
private static final String DB_SERVICE = "dbService";
private List<String> readMethodList = new ArrayList<String>();
private List<String> writeMethodList = new ArrayList<String>();
public Object readOrWriteDB(ProceedingJoinPoint pjp) throws Throwable {
String methodName = pjp.getSignature().getName();
if (isChooseReadDB(methodName)) {
//选择slave数据源
DataSourceHolder.setDataSource("data1");
} else if (isChooseWriteDB(methodName)) {
//选择master数据源
DataSourceHolder.setDataSource("data2");
} else {
//选择master数据源
DataSourceHolder.setDataSource("data1");
}
return pjp.proceed();
}
private boolean isChooseWriteDB(String methodName) {
for (String mappedName : this.writeMethodList) {
if (isMatch(methodName, mappedName)) {
return true;
}
}
return false;
}
private boolean isChooseReadDB(String methodName) {
for (String mappedName : this.readMethodList) {
if (isMatch(methodName, mappedName)) {
return true;
}
}
return false;
}
private boolean isMatch(String methodName, String mappedName) {
return PatternMatchUtils.simpleMatch(mappedName, methodName);
}
public List<String> getReadMethodList() {
return readMethodList;
}
public void setReadMethodList(List<String> readMethodList) {
this.readMethodList = readMethodList;
}
public List<String> getWriteMethodList() {
return writeMethodList;
}
public void setWriteMethodList(List<String> writeMethodList) {
this.writeMethodList = writeMethodList;
}
一般来说,是一主多从,即一个master库,多个slave库的,所以还得解决多个slave库之间负载均衡、故障转移以及失败重连接等问题。
1、负载均衡问题,slave不多,系统并发读不高的话,直接使用随机数访问也是可以的。就是根据slave的台数,然后产生随机数,随机的访问slave。
2、故障转移,如果发现connection获取不到了,则把它从slave列表中移除,等其回复后,再加入到slave列表中
3、失败重连,第一次连接失败后,可以多尝试几次,如尝试10次。
spring读写分离(配置多数据源)[marked]的更多相关文章
- Spring配置动态数据源-读写分离和多数据源
在现在互联网系统中,随着用户量的增长,单数据源通常无法满足系统的负载要求.因此为了解决用户量增长带来的压力,在数据库层面会采用读写分离技术和数据库拆分等技术.读写分离就是就是一个Master数据库,多 ...
- MySQL主从同步、读写分离配置步骤、问题解决笔记
MySQL主从同步.读写分离配置步骤.问题解决笔记 根据要求配置MySQL主从备份.读写分离,结合网上的文档,对搭建的步骤和出现的问题以及解决的过程做了如下笔记: 现在使用的两台服务器已经 ...
- MySQL主从及读写分离配置
<<MySQL主从又叫做Replication.AB复制.简单讲就是A和B两台机器做主从后,在A上写数据,B也会跟着写数据,两者数据实时同步>> MySQL主从是基于binlo ...
- MySQL5.6 Replication主从复制(读写分离) 配置完整版
MySQL5.6 Replication主从复制(读写分离) 配置完整版 MySQL5.6主从复制(读写分离)教程 1.MySQL5.6开始主从复制有两种方式: 基于日志(binlog): 基于GTI ...
- Mysql一主多从和读写分离配置简记
近期开发的系统中使用MySQL作为数据库,由于数据涉及到Money,所以不得不慎重.同时,用户对最大访问量也提出了要求.为了避免Mysql成为性能瓶颈并具备很好的容错能力,特此实现主从热备和读写分离. ...
- yii2的数据库读写分离配置
简介 数据库读写分离是在网站遇到性能瓶颈的时候最先考虑优化的步骤,那么yii2是如何做数据库读写分离的呢?本节教程来给大家普及一下yii2的数据库读写分离配置. 两个服务器的数据同步是读写分离的前提条 ...
- Mycat入门配置_读写分离配置
1.Mycat的分片 两台数据库服务器: 192.168.80.11 192.168.80.4 操作系统版本环境:centos6.5 数据库版本:5.6 mycat版本:1.4 release 数据库 ...
- mysql读写分离配置(整理)
mysql读写分离配置 环境:centos7.2 mysql5.7 场景描述: 数据库Master主服务器:192.168.206.100 数据库Slave从服务器:192.168.206.200 M ...
- MySQL+MyCat分库分表 读写分离配置
一. MySQL+MyCat分库分表 1 MyCat简介 java编写的数据库中间件 Mycat运行环境需要JDK. Mycat是中间件.运行在代码应用和MySQL数据库之间的应用. 前身 : cor ...
随机推荐
- cordova /phonegap 自定义插件
### cordova /phonegap 自定义插件 在使用cordova 的过程中,虽然官方提供的插件以及其他人开源的插件较多.但有时为了实现某种需求,还是需要自己编写插件. 以前总是会手动的配置 ...
- Linux 的多线程编程的高效开发经验
http://www.ibm.com/developerworks/cn/linux/l-cn-mthreadps/ 背景 Linux 平台上的多线程程序开发相对应其他平台(比如 Windows)的多 ...
- JavaScript之setcookie()讲解
function setcookie(name,value){ var Days = 30; var exp = new Date(); exp ...
- HDOJ 1220 Cube
CubeTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submiss ...
- 通过HTML条件注释判断IE版本的HTML语句详解<!--[if IE]> <![endif]-->
我们常常会在网页的HTML里面看到形如[if lte IE 9]……[endif]的代码,表示的是限定某些浏览器版本才能执行的语句,那么这些判断语句的规则是什么呢?请看下文: <!--[if ! ...
- C#&java重学笔记(面向对象)
C#部分 1.C#有一个internal关键字,指字段可以同一个程序集中访问,出了程序集不行.还有一个protected internal(没有先后之分)修饰词,指只能在同一个程序集中的子类访问 2. ...
- HDU 4006 The kth great number(multiset(或者)优先队列)
题目 询问第K大的数 //这是我最初的想法,用multiset,AC了——好吧,也许是数据弱也有可能 //multiset运用——不去重,边插入边排序 //iterator的运用,插入的时候,如果是相 ...
- HDU 4597 Play Game(记忆化搜索,深搜)
题目 //传说中的记忆化搜索,好吧,就是用深搜//多做题吧,,这个解法是搜来的,蛮好理解的 //题目大意:给出两堆牌,只能从最上和最下取,然后两个人轮流取,都按照自己最优的策略,//问说第一个人对多的 ...
- isMobile 一个简单的JS库,用来检测移动设备
点这里 github地址:https://github.com/kaimallea/isMobile Example Usage I include the minified version of t ...
- POJ 2109
#include<iostream> #include<stdio.h> #include<math.h> using namespace std; int mai ...