Mybatis+Spring实现Mysql读写分离
使用spring AbstractRoutingDatasource实现多数据源
public class DynamicDataSource extends AbstractRoutingDataSource {
//写数据源
private Object writeDataSource;
//读数据源
private Object readDataSource; @Override
public void afterPropertiesSet() {
Assert.isNull(writeDataSource, "Property 'writeDataSource' is required");
setDefaultTargetDataSource(writeDataSource);
Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
targetDataSources.put(DBTypeEnum.WRITE.name(), writeDataSource);
if (null != readDataSource)
targetDataSources.put(DBTypeEnum.READ.name(), readDataSource);
setTargetDataSources(targetDataSources);
super.afterPropertiesSet();
}
/**
* 获取当前使用那个数据源
*/
@Override
protected Object determineCurrentLookupKey() {
DBTypeEnum dataSource = DbContextHolder.getDbType();
if (null == dataSource || dataSource == DBTypeEnum.WRITE)
return DBTypeEnum.WRITE.name();
return DBTypeEnum.READ.name();
}
public Object getWriteDataSource() {
return writeDataSource;
}
public void setWriteDataSource(Object writeDataSource) {
this.writeDataSource = writeDataSource;
}
public Object getReadDataSource() {
return readDataSource;
}
public void setReadDataSource(Object readDataSource) {
this.readDataSource = readDataSource;
}
}
读写数据库类型
public enum DBTypeEnum {
WRITE, READ;
}
当前数据库配置上下文
public class DbContextHolder {
private static final ThreadLocal<DBTypeEnum> DATASOURCES = new ThreadLocal<DBTypeEnum>();
private DbContextHolder() {
}
/**
* 设置数据源
*
* @param dbType
*/
public static void setDbType(DBTypeEnum dbType) {
DATASOURCES.set(dbType.WRITE);
}
/*
* 获取当前数据源
* @return DBTypeEnum
* */
public static DBTypeEnum getDbType() {
return DATASOURCES.get();
}
/**
* 清除上下文数据
*/
public static void clearDbType() {
DATASOURCES.remove();
}
}
自定义事务管理器
public class DynamicDataSourceTransactionManager extends DataSourceTransactionManager {
/**
* 设置数据源
*/
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
boolean readOnly = definition.isReadOnly();
if (readOnly)
DbContextHolder.setDbType(DBTypeEnum.READ);
DbContextHolder.setDbType(DBTypeEnum.WRITE);
super.doBegin(transaction, definition);
}
/**
* 清理本地线程数据源
*/
@Override
protected void doCleanupAfterCompletion(Object transaction) {
super.doCleanupAfterCompletion(transaction);
DbContextHolder.clearDbType();
}
}
mybatis插件(拦截器)
@Intercepts({
@Signature(type = Executor.class, method = "update", args = {
MappedStatement.class, Object.class}),
@Signature(type = Executor.class, method = "query", args = {
MappedStatement.class, Object.class, RowBounds.class,
ResultHandler.class})})
public class DynamicPlugin implements Interceptor {
private static final Logger _log = LoggerFactory.getLogger(DynamicPlugin.class);
private static final String REGEX = ".*insert\\u0020.*|.*delete\\u0020.*|.*update\\u0020.*";
private static final Map<String, DBTypeEnum> cachaMap = new HashMap<String, DBTypeEnum>();
@Override
public Object intercept(Invocation invocation) throws Throwable {
boolean isSynchronizationActive = TransactionSynchronizationManager.isSynchronizationActive();
if (!isSynchronizationActive) {
MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
DBTypeEnum dbTypeEnum = null;
if ((dbTypeEnum = cachaMap.get(ms.getId())) == null) {
//读方法
if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) {
//!selectKeu为自增id查询主键(SELECT LAST_INSERT_ID)方法,使用主库
if (ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX))
dbTypeEnum = DBTypeEnum.WRITE;
else {
BoundSql boundSql = ms.getSqlSource().getBoundSql(invocation.getArgs()[1]);
String sql = boundSql.getSql().toLowerCase(Locale.CHINA).replaceAll("[\\t\\n\\r]", " ");
if (sql.matches(REGEX))
dbTypeEnum = DBTypeEnum.WRITE;
dbTypeEnum = DBTypeEnum.READ;
}
} else {
dbTypeEnum = DBTypeEnum.WRITE;
}
_log.warn("设置方法[{}] use [{}] Strategy, SqlCommandType [{}]..", ms.getId(), dbTypeEnum.name(), ms.getSqlCommandType().name());
cachaMap.put(ms.getId(), dbTypeEnum);
}
DbContextHolder.setDbType(dbTypeEnum);
}
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
if (target instanceof Executor) {
return Plugin.wrap(target, this);
} else {
return target;
}
}
@Override
public void setProperties(Properties properties) {
}
}
Mybatis+Spring实现Mysql读写分离的更多相关文章
- 使用Spring实现MySQL读写分离(转)
使用Spring实现MySQL读写分离 为什么要进行读写分离 大量的JavaWeb应用做的是IO密集型任务, 数据库的压力较大, 需要分流 大量的应用场景, 是读多写少, 数据库读取的压力更大 一个很 ...
- 使用Spring实现MySQL读写分离
1. 为什么要进行读写分离 大量的JavaWeb应用做的是IO密集型任务, 数据库的压力较大, 需要分流 大量的应用场景, 是读多写少, 数据库读取的压力更大 一个很自然的思路是使用一主多从的数据库集 ...
- spring+mybatis+mysql5.7实现读写分离,主从复制
申明:请尽量与我本博文所有的软件版本保持一致,避免不必要的错误. 所用软件版本列表:MySQL 5.7spring5mybaties3.4.6 首先搭建一个完整的spring5+springMVC5+ ...
- MyBatis多数据源配置(读写分离)
原文:http://blog.csdn.net/isea533/article/details/46815385 MyBatis多数据源配置(读写分离) 首先说明,本文的配置使用的最直接的方式,实际用 ...
- Spring AOP 实现读写分离
原文地址:Spring AOP 实现读写分离 博客地址:http://www.extlight.com 一.前言 上一篇<MySQL 实现主从复制> 文章中介绍了 MySQL 主从复制的搭 ...
- SSM/SSH框架的MySQL 读写分离实现的一种简单方法
简介 MySQL已经是使用最为广泛的一种数据库,往往实际使用过程中,为实现高可用及高性能,项目会采用主丛复制的方式实现读写分离.MySQL本身支持复制,通过简单的配置即可实现一主多从的配置,具体实现可 ...
- 提高性能,MySQL 读写分离环境搭建
这是松哥之前一个零散的笔记,整理出来分享给大伙! MySQL 读写分离在互联网项目中应该算是一个非常常见的需求了.受困于 Linux 和 MySQL 版本问题,很多人经常会搭建失败,今天松哥就给大伙举 ...
- 提高性能,MySQL 读写分离环境搭建(一)
这是松哥之前一个零散的笔记,整理出来分享给大伙! MySQL 读写分离在互联网项目中应该算是一个非常常见的需求了.受困于 Linux 和 MySQL 版本问题,很多人经常会搭建失败,今天松哥就给大伙举 ...
- mysql读写分离(PHP类)
mysql读写分离(PHP类) 博客分类: php mysql 自己实现了php的读写分离,并且不用修改程序 优点:实现了读写分离,不依赖服务器硬件配置,并且都是可以配置read服务器,无限扩展 ...
随机推荐
- Python-进程(2)
目录 进程互斥锁 队列 堆栈 IPC(进程间通信) 生产者与消费者模型 进程互斥锁 通过之前的学习,我们千方百计的实现了程序的异步,让多个任务可以同时在几个进程中并发处理 他们之间的运行没有顺序,一旦 ...
- php中Sessions
PHP Sessions Session 中文译名叫做“会话”,其本来的含义是指有始有终的一系列动作/消息. PHP session 变量用于存储关于用户会话(session)的信息,或者更改用户会 ...
- iOS开发之IMP和SEL(方法和类的反射)
1.SEL:类方法的指针,相当于一种编号,区别与IMP! IMP:函数指针,保存了方法的地址! SEL是通过表取对应关系的IMP,进行方法的调用! 2.获取SEL和IMP方法和调用: SEL meth ...
- Git命令使用和配置
git config --global user.name "your name" git config --global user.email "your email& ...
- [原创]新版PageOffice V4.0为什么用弹出窗口的方式打开文件?
前的包含文档处理功能的Web办公系统,在打开文档的时候,一部分系统是采用Office文档嵌入到主窗口页面中右侧工作区域的方式,另一部分系统采用的是弹出新的浏览器窗口,里面完整的嵌入Office文件的打 ...
- AppScan的基础使用
AppScan是用于Web项目的安全测试工具,扫描网站所有url,自动测试是否存在各种类型的漏洞.AppScan安装在Windows环境上,版本越高,规则库越安全,扫描越全面. 1. 打开AppS ...
- Swagger发布服务器时错误 500 : { "Message": "An error has occurred." }
在做Web API的文档自动生成时,本机调试都正常,发布到服务器上出现500错误 500 : { "Message": "An error has occurred.&q ...
- Top- Linux必学的60个命令
1.作用 top命令用来显示执行中的程序进程,使用权限是所有用户. 2.格式 top [-] [d delay] [q] [c] [S] [s] [i] [n] 3.主要参数 d:指定更新的间隔,以秒 ...
- [TJOI2017]城市 【树的直径+暴力+优化】
Online Judge:Luogu P3761 Label:树的直径,暴力 题目描述 从加里敦大学城市规划专业毕业的小明来到了一个地区城市规划局工作.这个地区一共有n座城市,n-1条高速公路,保证了 ...
- 08.Hibernate的一级缓存-->>Session
Hibernate提供了两种缓存: 1.一级缓存:自带的不可卸载的,一级缓存的生命周期与Session一致,一级缓存成为Session级别的缓存 2.二级缓存:默认没有开启,需要手动配置才可以使用,二 ...