1、在Navicat把3個mysql連接好
2、把3306的mysql的數據庫備份
3、3380和3381數據庫新建數據庫
4、把備份好的數據導入3380和3381mysql裏
5、主庫配置
①、進入3380\data\my.ini
在my.ini修改:
#開啓主從複製,主庫的配置,指定二進制的日誌
#指定主庫serverid
server-id=80
#指定同步的數據庫,如果不指定則同步全部數據庫
binlog-do-db=taotao
②、重啓下3380服務
③、3380mysql(主庫)執行sql語句
SHOW MASTER STATUS
需要記錄下Position值,需要在從庫中設置同步起始值:
④、在3380mysql主庫創建同步用戶
#授權用戶slave01使用123456密碼登錄mysql
grant replication slave on *.* to 'slave01'@'127.0.0.1' identified by '123456';
flush privileges;
6、從庫配置
在my.ini修改:
#指定serverid,只要不重複即可,從庫也只有這一個配置,其他都在SQL語句中操作
server-id=81
以下執行SQL:
CHANGE MASTER TO
master_host='127.0.0.1',
master_user='slave01',
master_password='123456',
master_port=3380,
master_log_file='mysql-bin.000003',
master_log_pos=420;
#啓動slave同步
START SLAVE;
#查看同步狀態
執行sql語句:SHOW SLAVE STATUS;
結果:
這裏啓動複製失敗解決方案:
分析 -- 看日誌。
打開3381\logs\mysql.err.log文件
解決UUID問題
設置MySQL的UUID:打開3381\data\data\auto.cnf文件
這裏隨便修改一個數字或者字母即可:
重啓3381服務
然後:
至此,兩個mysql的數據庫表的數據已經連在一起,可以對3381數據庫的表進行修改,3380的表數據也同樣被修改了,下面就可以進行讀寫分離了。
1. 方案
解決讀寫分離的方案有兩種:應用層解決和中間件解決。
1.1. 應用層解決:
優點:
1、 多數據源切換方便,由程序自動完成;
2、 不需要引入中間件;
3、 理論上支持任何數據庫;
缺點:
1、 由程序員完成,運維參與不到;
2、 不能做到動態增加數據源;
1.2. 中間件解決
優缺點:
優點:
1、 源程序不需要做任何改動就可以實現讀寫分離;
2、 動態添加數據源不需要重啓程序;
缺點:
1、 程序依賴於中間件,會導致切換數據庫變得困難;
2、 由中間件做了中轉代理,性能有所下降;
相關中間件產品使用:
mysql-proxy:http://hi.baidu.com/geshuai2008/item/0ded5389c685645f850fab07
Amoeba for MySQL:http://www.iteye.com/topic/188598和http://www.iteye.com/topic/1113437
2. 使用Spring基於應用層實現
2.1. 原理
在進入Service之前,使用AOP來做出判斷,是使用寫庫還是讀庫,判斷依據可以根據方法名判斷,比如說以query、find、get等開頭的就走讀庫,其他的走寫庫。
代碼:
先寫3個類:
DynamicDataSource
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* 定義動態數據源,實現通過集成Spring提供的AbstractRoutingDataSource,只需要實現determineCurrentLookupKey方法即可
*
* 由於DynamicDataSource是單例的,線程不安全的,所以採用ThreadLocal保證線程安全,由DynamicDataSourceHolder完成。
*
* @author zhijun
*
*/
public class DynamicDataSource extends AbstractRoutingDataSource{
@Override
protected Object determineCurrentLookupKey() {
// 使用DynamicDataSourceHolder保證線程安全,並且得到當前線程中的數據源key
return DynamicDataSourceHolder.getDataSourceKey();
}
}
DynamicDataSourceHolder
/**
*
* 使用ThreadLocal技術來記錄當前線程中的數據源的key
*
* @author zhijun
*
*/
public class DynamicDataSourceHolder {
//寫庫對應的數據源key
private static final String MASTER = "master";
//讀庫對應的數據源key
private static final String SLAVE = "slave";
//使用ThreadLocal記錄當前線程的數據源key
private static final ThreadLocal<String> holder = new ThreadLocal<String>();
/**
* 設置數據源key
* @param key
*/
public static void putDataSourceKey(String key) {
holder.set(key);
}
/**
* 獲取數據源key
* @return
*/
public static String getDataSourceKey() {
return holder.get();
}
/**
* 標記寫庫
*/
public static void markMaster(){
putDataSourceKey(MASTER);
}
/**
* 標記讀庫
*/
public static void markSlave(){
putDataSourceKey(SLAVE);
}
}
DataSourceAspect
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
/**
* 定義數據源的AOP切面,通過該Service的方法名判斷是應該走讀庫還是寫庫
*
* @author zhijun
*
*/
public class DataSourceAspect {
/**
* 在進入Service方法之前執行
*
* @param point 切面對象
*/
public void before(JoinPoint point) {
// 獲取到當前執行的方法名
String methodName = point.getSignature().getName();
if (isSlave(methodName)) {
// 標記爲讀庫
DynamicDataSourceHolder.markSlave();
} else {
// 標記爲寫庫
DynamicDataSourceHolder.markMaster();
}
}
/**
* 判斷是否爲讀庫
*
* @param methodName
* @return
*/
private Boolean isSlave(String methodName) {
// 方法名以query、find、get開頭的方法名走從庫
return StringUtils.startsWithAny(methodName, "query", "find", "get");
}
}
修改jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/taotao?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
jdbc.username=root
jdbc.password=root
jdbc.master.driver=com.mysql.jdbc.Driver
jdbc.master.url=jdbc:mysql://127.0.0.1:3380/taotao?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
jdbc.master.username=root
jdbc.master.password=root
jdbc.slave01.driver=com.mysql.jdbc.Driver
jdbc.slave01.url=jdbc:mysql://127.0.0.1:3381/taotao?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
jdbc.slave01.username=root
jdbc.slave01.password=root
定義連接池(修改applicationContext.xml)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" 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-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 使用spring自帶的佔位符替換功能 -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!-- 允許JVM參數覆蓋 -->
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<!-- 忽略沒有找到的資源文件 -->
<property name="ignoreResourceNotFound" value="true" />
<!-- 配置資源文件 -->
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:upload.properties</value>
<value>classpath:redis.properties</value>
<value>classpath:env.properties</value>
<value>classpath:httpclinet.properties</value>
<value>classpath:rabbitmq.properties</value>
</list>
</property>
</bean>
<!-- 掃描包 -->
<context:component-scan base-package="com.taotao"/>
<!-- 定義數據源 -->
<!-- <bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource"
destroy-method="close">
數據庫驅動
<property name="driverClass" value="${jdbc.driver}" />
相應驅動的jdbcUrl
<property name="jdbcUrl" value="${jdbc.url}" />
數據庫的用戶名
<property name="username" value="${jdbc.username}" />
數據庫的密碼
<property name="password" value="${jdbc.password}" />
檢查數據庫連接池中空閒連接的間隔時間,單位是分,默認值:240,如果要取消則設置爲0
<property name="idleConnectionTestPeriod" value="60" />
連接池中未使用的鏈接最大存活時間,單位是分,默認值:60,如果要永遠存活設置爲0
<property name="idleMaxAge" value="30" />
每個分區最大的連接數
判斷依據:請求併發數
<property name="maxConnectionsPerPartition" value="100" />
每個分區最小的連接數
<property name="minConnectionsPerPartition" value="5" />
</bean> -->
<!-- 配置連接池 -->
<bean id="masterDataSource" class="com.jolbox.bonecp.BoneCPDataSource"
destroy-method="close">
<!-- 數據庫驅動 -->
<property name="driverClass" value="${jdbc.master.driver}" />
<!-- 相應驅動的jdbcUrl -->
<property name="jdbcUrl" value="${jdbc.master.url}" />
<!-- 數據庫的用戶名 -->
<property name="username" value="${jdbc.master.username}" />
<!-- 數據庫的密碼 -->
<property name="password" value="${jdbc.master.password}" />
<!-- 檢查數據庫連接池中空閒連接的間隔時間,單位是分,默認值:240,如果要取消則設置爲0 -->
<property name="idleConnectionTestPeriod" value="60" />
<!-- 連接池中未使用的鏈接最大存活時間,單位是分,默認值:60,如果要永遠存活設置爲0 -->
<property name="idleMaxAge" value="30" />
<!-- 每個分區最大的連接數 -->
<property name="maxConnectionsPerPartition" value="150" />
<!-- 每個分區最小的連接數 -->
<property name="minConnectionsPerPartition" value="5" />
</bean>
<!-- 配置連接池 -->
<bean id="slave01DataSource" class="com.jolbox.bonecp.BoneCPDataSource"
destroy-method="close">
<!-- 數據庫驅動 -->
<property name="driverClass" value="${jdbc.slave01.driver}" />
<!-- 相應驅動的jdbcUrl -->
<property name="jdbcUrl" value="${jdbc.slave01.url}" />
<!-- 數據庫的用戶名 -->
<property name="username" value="${jdbc.slave01.username}" />
<!-- 數據庫的密碼 -->
<property name="password" value="${jdbc.slave01.password}" />
<!-- 檢查數據庫連接池中空閒連接的間隔時間,單位是分,默認值:240,如果要取消則設置爲0 -->
<property name="idleConnectionTestPeriod" value="60" />
<!-- 連接池中未使用的鏈接最大存活時間,單位是分,默認值:60,如果要永遠存活設置爲0 -->
<property name="idleMaxAge" value="30" />
<!-- 每個分區最大的連接數 -->
<property name="maxConnectionsPerPartition" value="150" />
<!-- 每個分區最小的連接數 -->
<property name="minConnectionsPerPartition" value="5" />
</bean>
<!-- 定義數據源,使用自己實現的數據源 -->
<bean id="dataSource" class="com.taotao.manage.datasource.DynamicDataSource">
<!-- 設置多個數據源 -->
<property name="targetDataSources">
<map key-type="java.lang.String">
<!-- 這個key需要和程序中的key一致 -->
<entry key="master" value-ref="masterDataSource"/>
<entry key="slave" value-ref="slave01DataSource"/>
</map>
</property>
<!-- 設置默認的數據源,這裏默認走寫庫 -->
<property name="defaultTargetDataSource" ref="masterDataSource"/>
</bean>
</beans>
配置事務管理以及動態切換數據源切面
定義事務管理器(如果有了可以不用再定義)
<!-- 定義事務管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
定義事務策略(如果有了可以不用再定義)
<!-- 定義事務策略 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--定義查詢方法都是隻讀的 -->
<tx:method name="query*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="get*" read-only="true" />
<!-- 主庫執行操作,事務傳播行爲定義爲默認行爲 -->
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<!--其他方法使用默認事務策略 -->
<tx:method name="*" />
</tx:attributes>
</tx:advice>
定義切面(修改applicationContext-transaction.xml)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" 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-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 定義事務管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 定義事務策略 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--所有以query開頭的方法都是隻讀的 -->
<tx:method name="query*" read-only="true" />
<!--其他方法使用默認事務策略 -->
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<!-- 定義AOP切面處理器 -->
<bean class="com.taotao.manage.datasource.DataSourceAspect" id="dataSourceAspect" />
<aop:config>
<!--pointcut元素定義一個切入點,execution中的第一個星號 用以匹配方法的返回類型,
這裏星號表明匹配所有返回類型。 com.abc.dao.*.*(..)表明匹配cn.itcast.mybatis.service包下的所有類的所有
方法 -->
<aop:pointcut id="myPointcut" expression="execution(* com.taotao.manage.service.*.*(..))" />
<!--將定義好的事務處理策略應用到上述的切入點 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut" />
<!-- 將切面應用到自定義的切面處理器上,-9999保證該切面優先級最高執行 -->
<aop:aspect ref="dataSourceAspect" order="-9999">
<aop:before method="before" pointcut-ref="myPointcut" />
</aop:aspect>
</aop:config>
</beans>
至此,讀寫分離已經實現完成。需要改進的可以再往下學習:
3. 改進切面實現,使用事務策略規則匹配
之前的實現我們是將通過方法名匹配,而不是使用事務策略中的定義,我們使用事務管理策略中的規則匹配。
3.1. 改進後的配置
<!-- 定義AOP切面處理器 -->
<bean class="cn.itcast.usermanage.spring.DataSourceAspect" id="dataSourceAspect">
<!-- 指定事務策略 -->
<property name="txAdvice" ref="txAdvice"/>
<!-- 指定slave方法的前綴(非必須) -->
<property name="slaveMethodStart" value="query,find,get"/>
</bean>
3.2. 改進後的實現
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionAttribute;
import org.springframework.transaction.interceptor.TransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionInterceptor;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.ReflectionUtils;
/**
* 定義數據源的AOP切面,該類控制了使用Master還是Slave。
*
* 如果事務管理中配置了事務策略,則採用配置的事務策略中的標記了ReadOnly的方法是用Slave,其它使用Master。
*
* 如果沒有配置事務管理的策略,則採用方法名匹配的原則,以query、find、get開頭方法用Slave,其它用Master。
*
* @author zhijun
*
*/
public class DataSourceAspect {
private List<String> slaveMethodPattern = new ArrayList<String>();
private static final String[] defaultSlaveMethodStart = new String[]{ "query", "find", "get" };
private String[] slaveMethodStart;
/**
* 讀取事務管理中的策略
*
* @param txAdvice
* @throws Exception
*/
@SuppressWarnings("unchecked")
public void setTxAdvice(TransactionInterceptor txAdvice) throws Exception {
if (txAdvice == null) {
// 沒有配置事務管理策略
return;
}
//從txAdvice獲取到策略配置信息
TransactionAttributeSource transactionAttributeSource = txAdvice.getTransactionAttributeSource();
if (!(transactionAttributeSource instanceof NameMatchTransactionAttributeSource)) {
return;
}
//使用反射技術獲取到NameMatchTransactionAttributeSource對象中的nameMap屬性值
NameMatchTransactionAttributeSource matchTransactionAttributeSource = (NameMatchTransactionAttributeSource) transactionAttributeSource;
Field nameMapField = ReflectionUtils.findField(NameMatchTransactionAttributeSource.class, "nameMap");
nameMapField.setAccessible(true); //設置該字段可訪問
//獲取nameMap的值
Map<String, TransactionAttribute> map = (Map<String, TransactionAttribute>) nameMapField.get(matchTransactionAttributeSource);
//遍歷nameMap
for (Map.Entry<String, TransactionAttribute> entry : map.entrySet()) {
if (!entry.getValue().isReadOnly()) {//判斷之後定義了ReadOnly的策略才加入到slaveMethodPattern
continue;
}
slaveMethodPattern.add(entry.getKey());
}
}
/**
* 在進入Service方法之前執行
*
* @param point 切面對象
*/
public void before(JoinPoint point) {
// 獲取到當前執行的方法名
String methodName = point.getSignature().getName();
boolean isSlave = false;
if (slaveMethodPattern.isEmpty()) {
// 當前Spring容器中沒有配置事務策略,採用方法名匹配方式
isSlave = isSlave(methodName);
} else {
// 使用策略規則匹配
for (String mappedName : slaveMethodPattern) {
if (isMatch(methodName, mappedName)) {
isSlave = true;
break;
}
}
}
if (isSlave) {
// 標記爲讀庫
DynamicDataSourceHolder.markSlave();
} else {
// 標記爲寫庫
DynamicDataSourceHolder.markMaster();
}
}
/**
* 判斷是否爲讀庫
*
* @param methodName
* @return
*/
private Boolean isSlave(String methodName) {
// 方法名以query、find、get開頭的方法名走從庫
return StringUtils.startsWithAny(methodName, getSlaveMethodStart());
}
/**
* 通配符匹配
*
* Return if the given method name matches the mapped name.
* <p>
* The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, as well as direct
* equality. Can be overridden in subclasses.
*
* @param methodName the method name of the class
* @param mappedName the name in the descriptor
* @return if the names match
* @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String)
*/
protected boolean isMatch(String methodName, String mappedName) {
return PatternMatchUtils.simpleMatch(mappedName, methodName);
}
/**
* 用戶指定slave的方法名前綴
* @param slaveMethodStart
*/
public void setSlaveMethodStart(String[] slaveMethodStart) {
this.slaveMethodStart = slaveMethodStart;
}
public String[] getSlaveMethodStart() {
if(this.slaveMethodStart == null){
// 沒有指定,使用默認
return defaultSlaveMethodStart;
}
return slaveMethodStart;
}
}
4. 一主多從的實現
很多實際使用場景下都是採用“一主多從”的架構的,所有我們現在對這種架構做支持,目前只需要修改DynamicDataSource即可。
4.1. 實現
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.util.ReflectionUtils;
/**
* 定義動態數據源,實現通過集成Spring提供的AbstractRoutingDataSource,只需要實現determineCurrentLookupKey方法即可
*
* 由於DynamicDataSource是單例的,線程不安全的,所以採用ThreadLocal保證線程安全,由DynamicDataSourceHolder完成。
*
* @author zhijun
*
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
private static final Logger LOGGER = LoggerFactory.getLogger(DynamicDataSource.class);
private Integer slaveCount;
// 輪詢計數,初始爲-1,AtomicInteger是線程安全的
private AtomicInteger counter = new AtomicInteger(-1);
// 記錄讀庫的key
private List<Object> slaveDataSources = new ArrayList<Object>(0);
@Override
protected Object determineCurrentLookupKey() {
// 使用DynamicDataSourceHolder保證線程安全,並且得到當前線程中的數據源key
if (DynamicDataSourceHolder.isMaster()) {
Object key = DynamicDataSourceHolder.getDataSourceKey();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("當前DataSource的key爲: " + key);
}
return key;
}
Object key = getSlaveKey();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("當前DataSource的key爲: " + key);
}
return key;
}
@SuppressWarnings("unchecked")
@Override
public void afterPropertiesSet() {
super.afterPropertiesSet();
// 由於父類的resolvedDataSources屬性是私有的子類獲取不到,需要使用反射獲取
Field field = ReflectionUtils.findField(AbstractRoutingDataSource.class, "resolvedDataSources");
field.setAccessible(true); // 設置可訪問
try {
Map<Object, DataSource> resolvedDataSources = (Map<Object, DataSource>) field.get(this);
// 讀庫的數據量等於數據源總數減去寫庫的數量
this.slaveCount = resolvedDataSources.size() - 1;
for (Map.Entry<Object, DataSource> entry : resolvedDataSources.entrySet()) {
if (DynamicDataSourceHolder.MASTER.equals(entry.getKey())) {
continue;
}
slaveDataSources.add(entry.getKey());
}
} catch (Exception e) {
LOGGER.error("afterPropertiesSet error! ", e);
}
}
/**
* 輪詢算法實現
*
* @return
*/
public Object getSlaveKey() {
// 得到的下標爲:0、1、2、3……
Integer index = counter.incrementAndGet() % slaveCount;
if (counter.get() > 9999) { // 以免超出Integer範圍
counter.set(-1); // 還原
}
return slaveDataSources.get(index);
}
}
參考資料
http://www.iteye.com/topic/1127642
http://634871.blog.51cto.com/624871/1329301