---
title: "spring+mybatis利用interceptor(plugin)实现数据库读写分离"
author: "xiaoZ5919"
date: "2012-04-24T22:28:26Z"
tags: []
categories: ["企业架构"]
slug: "spring-mybatis-interceptor-plugin"
draft: false
lastmod: "2012-04-24T22:23:49Z"
id: 1497223
url: "https://xiaoz5919.iteye.com/blog/1497223"
---

**1. 前提**

    好长时间不写博客了，应该吐槽，写点什么东西了！最近在研究数据库读写分离，分表分库的一些东西。其实这个问题好早之前就想好，只是以前使用hibernate，难点是不好判断什么样的sql走读库，什么样的sql走主库？用正则匹配开头或许可以，/^select 没想出什么好的解决方法，mybatis就不一样了，mappedstatement有commandtype属性，象select，update，delete等类型，为实现读写分离打下来良好的基础。

**2. 解决方法**

    LazyConnectionProxy + RoutingDataSource +   Plugin

在SqlSessionTemplate，创建DefaultSqlSession的时候，使用connection proxy的代理，这时并没有真正的获取connection，因为我们不知道是要取读还是写的数据源。待到StatementHandler的prepare()使用connection创建PreparedStatement的时候再根据mappedstatement的commandType去路由获取真实的connection。

   RoutingDataSource支持一主一从，或者一主多从并采用round robin的方式简单负载均衡，预留接口路由和负载均衡策略可自定义。

   不支持事务，适合auto commit为true的场景。表述能力不强，有兴趣的可以看看代码，欢迎拍砖！

    [http://code.google.com/p/rwmybatis/](http://code.google.com/p/rwmybatis/)