Mycat入門和讀寫分離實戰

1.什麼是MyCat

        MyCAT是一款由阿里Cobar演變而來的用於支持數據庫,讀寫分離、分表分庫的分佈式中間件。MyCAT支持Oracle、MSSQL、MYSQL、PG、DB2關係型數據庫,同時也支持MongoDB等非關係型數據庫。
        MyCAT原理MyCAT主要是通過對SQL的攔截,然後經過一定規則的分片解析、路由分析、讀寫分離分析、緩存分析等,然後將SQL發給後端真實的數據塊,並將返回的結果做適當處理返回給客戶端。

2.基於MyCat實現讀寫分離

       讀寫分離,簡單地說是把對數據庫的讀和寫操作分開,以對應不同的數據庫服務器。主數據庫提供寫操作,從數據庫提供讀操作,這樣能有效地減輕單臺數據庫的壓力。主數據庫進行寫操作後,數據及時同步到所讀的數據庫,儘可能保證讀、寫數據庫的數據一致,比如MySQL的主從複製、Oracle的data guard、SQL Server的複製訂閱等。

3.安裝Mycat

安裝前準備
三臺服務器(關閉防火牆)
mycat安裝服務器:192.168.223.140
主數據庫:192.168.223.141
從數據庫:192.168.223.142
讀寫分離前提是:實現主從複製,主從複製請參考《主從複製原理》

1、上傳安裝Mycat-server-1.6.5-release-20180122220033-linux.tar
2、解壓安裝包tar –zxvf  Mycat-server-1.6.5-release-20180122220033-linux.tar
3、配置schema.xml 和server.xml
4、客戶端連接端口號: 8066

配置文件介紹:
在這裏插入圖片描述
具體配置:我們這個列子只用到了schema.xml和server.xml

schema.xml 配置如下:

<?xml version="1.0"?>
<!DOCTYPE mycat:schema SYSTEM "schema.dtd">
<mycat:schema xmlns:mycat="http://io.mycat/">
<!--dataNode節點中各屬性說明:
    name:指定邏輯數據節點名稱;
    dataHost:指定邏輯數據節點物理主機節點名稱;
    database:指定物理主機節點上。如果一個節點上有多個庫,可使用表達式db$0-99,     表示指定0-99100個數據庫;
-->
    <!-- seckill是mycat的邏輯庫名稱,鏈接需要用的 -->
    <schema name="seckill" checkSQLschema="false" sqlMaxLimit="100" dataNode="dn1"></schema>
        <!-- database 是MySQL數據庫的庫名 -->
    <dataNode name="dn1" dataHost="localhost" database="seckill" />
    <!--
    dataHost 節點中各屬性說明:
        name:物理主機節點名稱;
        maxCon:指定物理主機服務最大支持1000個連接;
        minCon:指定物理主機服務最小保持10個連接;
        writeType:指定寫入類型;
            0,只在writeHost節點寫入;
            1,在所有節點都寫入。慎重開啓,多節點寫入順序爲默認寫入根據配置順序,第一個掛掉切換另一個;
        dbType:指定數據庫類型;
        dbDriver:指定數據庫驅動;
        balance:指定物理主機服務的負載模式。
            0,不開啓讀寫分離機制;
            1,全部的readHost與stand by writeHost參與select語句的負載均衡,簡單的說,當雙主雙從模式(M1->S1M2->S2,並且M1M2互爲主備),正常情況下,M2,S1,S2都參與select語句的負載均衡;
            2,所有的readHost與writeHost都參與select語句的負載均衡,也就是說,當系統的寫操作壓力不大的情況下,所有主機都可以承擔負載均衡;
-->
    <dataHost name="localhost" maxCon="1000" minCon="10" balance="3" writeType="0" dbType="mysql" dbDriver="native" switchType="1"  slaveThreshold="100">
        <heartbeat>select user()</heartbeat>
        <!-- 可以配置多個主從 -->
        <writeHost host="hostM1" url="192.168.223.141:3306" user="root" password="123456">
            <!-- 可以配置多個從庫 -->
            <readHost host="hostS2" url="192.168.223.142:3306" user="root" password="123456" />
        </writeHost>
    </dataHost>
</mycat:schema>

建議:mycat邏輯庫名稱和mysql數據庫名稱一樣,否則可能會存在連接不上問題
server.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<!-- - - Licensed under the Apache License, Version 2.0 (the "License"); 
	- you may not use this file except in compliance with the License. - You 
	may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 
	- - Unless required by applicable law or agreed to in writing, software - 
	distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 
	WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the 
	License for the specific language governing permissions and - limitations 
	under the License. -->
<!DOCTYPE mycat:server SYSTEM "server.dtd">
<mycat:server xmlns:mycat="http://io.mycat/">
   

   <!-- 讀寫都可用的用戶 -->
    <user name="root" defaultAccount="true">
        <property name="password">123456</property>
        <property name="schemas">seckill</property>

        <!-- 表級 DML 權限設置 -->
        <!--        
        <privileges check="false">
            <schema name="TESTDB" dml="0110" >
                <table name="tb01" dml="0000"></table>
                <table name="tb02" dml="1111"></table>
            </schema>
        </privileges>       
         -->
    </user>

    <!-- 只讀用戶 -->
    <user name="user">
        <property name="password">123456</property>
        <property name="schemas">seckill</property>
        <property name="readOnly">true</property>
    </user>

</mycat:server>

root用戶可以讀寫,user用戶只可以讀

驗證:root和user的權限,用user用戶無法寫入,用root用戶可讀可寫就不截圖了。
在這裏插入圖片描述

4.Springboot整合Mycat實現讀寫分離

spring:
  datasource:
    ###可讀數據源
    select:
      jdbc-url: jdbc:mysql://192.168.223.140:8066/seckill
      driver-class-name: com.mysql.jdbc.Driver
      username: user
      password: 123456
    ####可寫數據源  
    update:
      jdbc-url: jdbc:mysql://192.168.223.140:8066/seckill
      driver-class-name: com.mysql.jdbc.Driver
      username: root
      password: 123456
    type: com.alibaba.druid.pool.DruidDataSource

多數據源:一種是註解,另一種是指定前綴
指定前綴:
DataSourceConfig

@Configuration
public class DataSourceConfig {

	// 創建可讀數據源
	@Bean(name = "selectDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.select") // application.properteis中對應屬性的前綴
	public DataSource dataSource1() {
		return DataSourceBuilder.create().build();
	}

	// 創建可寫數據源
	@Bean(name = "updateDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.update") // application.properteis中對應屬性的前綴
	public DataSource dataSource2() {
		return DataSourceBuilder.create().build();
	}
}

DataSourceContextHolder

@Component
@Lazy(false)
public class DataSourceContextHolder {
	// 採用ThreadLocal 保存本地多數據源
	private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

	// 設置數據源類型
	public static void setDbType(String dbType) {
		contextHolder.set(dbType);
	}

	public static String getDbType() {
		return contextHolder.get();
	}

	public static void clearDbType() {
		contextHolder.remove();
	}

}

DynamicDataSource

@Component
@Primary
public class DynamicDataSource extends AbstractRoutingDataSource {
	@Autowired
	@Qualifier("selectDataSource")
	private DataSource selectDataSource;

	@Autowired
	@Qualifier("updateDataSource")
	private DataSource updateDataSource;

	/**
	 * 這個是主要的方法,返回的是生效的數據源名稱
	 */
	@Override
	protected Object determineCurrentLookupKey() {
		System.out.println("DataSourceContextHolder:::" + DataSourceContextHolder.getDbType());
		return DataSourceContextHolder.getDbType();
	}

	/**
	 * 配置數據源信息
	 */
	@Override
	public void afterPropertiesSet() {
		Map<Object, Object> map = new HashMap<>();
		map.put("selectDataSource", selectDataSource);
		map.put("updateDataSource", updateDataSource);
		setTargetDataSources(map);
		setDefaultTargetDataSource(updateDataSource);
		super.afterPropertiesSet();
	}
}

SwitchDataSourceAOP

@Aspect
@Component
@Lazy(false)
@Order(0) // Order設定AOP執行順序 使之在數據庫事務上先執行
public class SwitchDataSourceAOP {
	// 這裏切到你的方法目錄
	@Before("execution(* com.mayikt.service.*.*(..))")
	public void process(JoinPoint joinPoint) {
		String methodName = joinPoint.getSignature().getName();
		if (methodName.startsWith("get") || methodName.startsWith("count") || methodName.startsWith("find")
				|| methodName.startsWith("list") || methodName.startsWith("select") || methodName.startsWith("check")) {
			// 讀
			DataSourceContextHolder.setDbType("selectDataSource");
		} else {
			// 切換dataSource
			DataSourceContextHolder.setDbType("updateDataSource");
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章