SpringBoot微服務 +tomcat叢集+Ngnix負載均衡+Mysql主從複製,讀寫分離(4)
阿新 • • 發佈:2019-01-01
四:mysql主從複製,讀寫分離
1.首先把mysql原始碼包檔案拷到兩臺linux伺服器上,然後在兩臺伺服器上安裝Mysql資料庫
2.安裝完畢以後配置主從資料庫 主資料只負載寫資料 從資料庫只負責讀資料安裝 MySQL 1 安裝 ncurses Ncurses 提供字元終端處理庫,包括面板和選單。它提供了一套控制游標,建立 視窗,改變前景背景顏色以及處理滑鼠操作的函式。使使用者在字元終端下編寫應 用程式時繞過了那些惱人的底層機制。簡而言之,他是一個可以使應用程式直接 控制終端螢幕顯示的函式庫。 1、 yum -y install ncurses-devel 注:如果報錯,包找不到,是*萬用字元沒有識別,給檔名加雙引號 “ncurses*” 2、原始碼編譯: cd /lamp/ncurses-5.9 ./configure --with-shared --without-debug --without-ada --enable-overwrite make make install * 若不安裝 ncurses 編譯 MySQL 時會報錯 * --without-ada 引數為設定不編譯為 ada 繫結,因進入 chroot 環境不能使用 ada ; --enable-overwrite 引數為定義把標頭檔案安裝到/tools/include 下而不是 /tools/include/ncurses 目錄 * --with-shared 生成共享庫 2.安裝 cmake 和 bison mysql 在 5.5 以後,不再使用./configure 工具,進行編譯安裝。而使用 cmake 工具替代 了./configure 工具。cmake 的具體用法參考文件 cmake 說明。 bison 是一個自由軟體,用於自動生成語法分析器程式,可用於所有常見的操作系 統 yum -y install cmake yum -y install bison 3. 安裝 MySQL 偽使用者 mysql 當安裝Apache已經存在 groupadd mysql useradd -g mysql mysql * 新增使用者組 mysql ,將 mysql 使用者預設組設定為 mysql 使用者組 cd /lamp/mysql-5.5.23 cmake -DCMAKE_INSTALL_PREFIX=/usr/local/mysql -DMYSQL_UNIX_ADDR=/tmp/mysql.sock -DEXTRA_CHARSETS=all -DDEFAULT_CHARSET=utf8 -DDEFAULT_COLLATION=utf8_general_ci -DWITH_MYISAM_STORAGE_ENGINE=1 -DWITH_INNOBASE_STORAGE_ENGINE=1 -DWITH_MEMORY_STORAGE_ENGINE=1 -DWITH_READLINE=1 -DENABLED_LOCAL_INFILE=1 -DMYSQL_USER=mysql -DMYSQL_TCP_PORT=3306 -DCMAKE_INSTALL_PREFIX=/usr/local/mysql 安裝位置 -DMYSQL_UNIX_ADDR=/tmp/mysql.sock 指定 socket(套接字)檔案位置 -DEXTRA_CHARSETS=all 擴充套件字元支援 -DDEFAULT_CHARSET=utf8 預設字符集 -DDEFAULT_COLLATION=utf8_general_ci 預設字元校對 -DWITH_MYISAM_STORAGE_ENGINE=1 安裝 myisam 儲存引擎 -DWITH_INNOBASE_STORAGE_ENGINE=1 安裝 innodb 儲存引擎 -DWITH_MEMORY_STORAGE_ENGINE=1 安裝 memory 儲存引擎 -DWITH_READLINE=1 支援 readline 庫 -DENABLED_LOCAL_INFILE=1 啟用載入本地資料 -DMYSQL_USER=mysql 指定 mysql 執行使用者 -DMYSQL_TCP_PORT=3306 指定 mysql 埠 make make install #如果報錯,清除快取,請使用以上命令 make clean rm -rf CMakeCache.txt #修改 mysql 目錄許可權 cd /usr/local/mysql/ chown -R mysql . chgrp -R mysql . #建立資料庫授權表, 初始化資料庫 /usr/local/mysql/scripts/mysql_install_db --user=mysql root /etc/passwd root user 表 mysql 庫 /usr/local/mysql/data #修改 mysql 目錄許可權 chown -R root . chown -R mysql data #複製 mysql 配置檔案 cp support-files/my-medium.cnf /etc/my.cnf #在進行初始化資料庫 /usr/local/mysql/scripts/mysql_install_db --user=mysql 4.啟動 MySQL 服務: 1.用原本原始碼的方式去使用和啟動 mysql /usr/local/mysql/bin/mysqld_safe --user=mysql & # &並且放入後臺 2.重啟Linux以後還要自啟動: vi /etc/rc.local /usr/local/mysql/bin/mysqladmin -uroot -p shutdown 關閉mysql /usr/local/mysql/bin/mysqld_safe --user=mysql & #此處的意思是使用mysql 使用者初始化 mysql資料庫 3.設定 mysql 密碼 * 給 mysql 使用者 root 加密碼 123 * 注意密碼不能寫成 “123” /usr/local/mysql/bin/mysqladmin -u root password 123 #此處的意思是使用mysql 使用者初始化 mysql資料庫 /usr/local/mysql/bin/mysql -u root -p #此處的意思是登陸mysql mysql>show databases; mysql>use test; mysql>show tables; mysql>\s #檢視字符集是否改為 utf8 * 進入 mysql 以後用 set 來改密碼 mysql> exit * 登入 MySQL 客戶端控制檯設定指定 root 密碼
二、把MySQL主伺服器192.168.117.118中的資料庫osyunweidb匯入到MySQL從伺服器192.168.117.119中 1、匯出資料庫osyunweidb #在MySQL主伺服器進行操作,匯出資料庫osyunweidb到/home/data5.sql mysqldump -u root -p --default-character-set=utf8 --opt -Q -R --skip-lock-tables osyunweidb > /home/data5.sql 備註:在匯出之前可以先進入MySQL控制檯執行下面命令 flush tables with read lock; #資料庫只讀鎖定命令,防止匯出資料庫的時候有資料寫入 unlock tables; #解除鎖定 #把home目錄下的data5.sql 資料庫檔案上傳到MySQL從伺服器的home目錄下面 scp /home/data5.sql
[email protected]:/home 系統運維 www.osyunwei.com 溫馨提醒:qihang01原創內容 版權所有,轉載請註明出處及原文連結 2、匯入資料庫到MySQL從伺服器 mysql -u root -p #進入從伺服器MySQL控制檯 create database osyunweidb; #建立資料庫 use osyunweidb #進入資料庫 source /home/data5.sql #匯入備份檔案到資料庫 mysql -u data5 -h 192.168.117.118 -p #測試在從伺服器上登入到主伺服器 三、配置MySQL主伺服器(192.168.117.118)的my.cnf檔案 vi /etc/my.cnf #編輯配置檔案,在[mysqld]部分新增下面內容 server-id=1 #設定伺服器id,為1表示主伺服器,注意:如果原來的配置檔案中已經有這一行,就不用再添加了。 log-bin=mysql-bin #啟動MySQ二進位制日誌系統,注意:如果原來的配置檔案中已經有這一行,就不用再添加了。 binlog-do-db=osyunweidb #需要同步的資料庫名,如果有多個數據庫,可重複此引數,每個資料庫一行 binlog-ignore-db=mysql #不同步mysql系統資料庫 :wq! #儲存退出 service mysqld restart #重啟MySQL mysql -u root -p #進入mysql控制檯 show variables like 'server_id'; #檢視server-id的值是否為1 mysql> show variables like 'server_id'; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | server_id | 1 | +---------------+-------+ 1 row in set (0.00 sec) show master status; #檢視主伺服器,出現以下類似資訊 mysql> show master status; +------------------+----------+--------------+------------------+ | File | Position | Binlog_Do_DB | Binlog_Ignore_DB | +------------------+----------+--------------+------------------+ | mysql-bin.000011 | 107 | osyunweidb | mysql | +------------------+----------+--------------+------------------+ 1 row in set (0.00 sec) 注意:這裡記住File的值:mysql-bin.000011和Position的值:107,後面會用到。 四、配置MySQL從伺服器(192.168.117.119)的my.cnf檔案 vi /etc/my.cnf #編輯配置檔案,在[mysqld]部分新增下面內容 server-id=2 #設定伺服器id,修改其值為2,表示為從資料庫 log-bin=mysql-bin #啟動MySQ二進位制日誌系統,注意:如果原來的配置檔案中已經有這一行,就不用再添加了。 replicate-do-db=osyunweidb #需要同步的資料庫名,如果有多個數據庫,可重複此引數,每個資料庫一行 replicate-ignore-db=mysql #不同步mysql系統資料庫 read_only #設定資料庫只讀 :wq! #儲存退出 service mysqld restart #重啟MySQL mysql -u root -p #進入MySQL控制檯 show variables like 'server_id'; #檢視server-id的值,必須為上面設定的2,否則請返回修改配置檔案 mysql> show variables like 'server_id'; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | server_id | 2 | +---------------+-------+ 1 row in set (0.01 sec) slave stop; #停止slave同步程序 change master to master_host='192.168.117.118',master_user='data5',master_password='123456', master_log_file='mysql-bin.000011' ,master_log_pos=107; #執行同步語句 slave start; #開啟slave同步程序 SHOW SLAVE STATUS\G #檢視slave同步資訊,出現以下內容 mysql> SHOW SLAVE STATUS\G *************************** 1. row *************************** Slave_IO_State: Waiting for master to send event Master_Host: 192.168.117.118 Master_User: data5 Master_Port: 3306 Connect_Retry: 60 Master_Log_File: mysql-bin.000011 Read_Master_Log_Pos: 107 Relay_Log_File: mysqlslave-relay-bin.000004 Relay_Log_Pos: 253 Relay_Master_Log_File: mysql-bin.000011 Slave_IO_Running: Yes Slave_SQL_Running: Yes Replicate_Do_DB: osyunweidb Replicate_Ignore_DB: mysql Replicate_Do_Table: Replicate_Ignore_Table: Replicate_Wild_Do_Table: Replicate_Wild_Ignore_Table: Last_Errno: 0 Last_Error: Skip_Counter: 0 Exec_Master_Log_Pos: 107 Relay_Log_Space: 560 Until_Condition: None Until_Log_File: Until_Log_Pos: 0 Master_SSL_Allowed: No Master_SSL_CA_File: Master_SSL_CA_Path: Master_SSL_Cert: Master_SSL_Cipher: Master_SSL_Key: Seconds_Behind_Master: 0 Master_SSL_Verify_Server_Cert: No Last_IO_Errno: 0 Last_IO_Error: Last_SQL_Errno: 0 Last_SQL_Error: Replicate_Ignore_Server_Ids: Master_Server_Id: 1 1 row in set (0.00 sec) mysql> 注意檢視: Slave_IO_Running: Yes Slave_SQL_Running: Yes 以上這兩個引數的值為Yes,即說明配置成功! 測試篇 測試MySQL主從伺服器是否正常執行 1、進入MySQL主伺服器(192.168.117.118) mysql -u root -p #進入MySQL控制檯 use osyunweidb #進入資料庫 CREATE TABLE test ( id int not null primary key,name char(20) ); #建立test表 2、進入MySQL從伺服器 mysql -u root -p #進入MySQL控制檯 use osyunweidb #進入資料庫 show tables; #檢視osyunweidb表結構,會看到有一個新建的表test,表示資料庫同步成功 mysql> show tables; +----------------------+ | Tables_in_osyunweidb | +----------------------+ | test | +----------------------+ 1 row in set (0.00 sec)
3.在java的配置檔案中配置兩個資料來源地址
4.在java配置檔案中進行資料來源配置管理
package com.company.test.base.config;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.alibaba.druid.pool.DruidDataSourceFactory;
/**
*
* springboot整合mybatis的基本入口 1)建立資料來源(如果採用的是預設的tomcat-jdbc資料來源,則不需要)
* 2)建立SqlSessionFactory 3)配置事務管理器,除非需要使用事務,否則不用配置
*/
@Configuration // 該註解類似於spring配置檔案
@MapperScan(basePackages = "com.company.test.dao") //配置mapper介面的位置
@EnableTransactionManagement //Spring事務管理器
public class MyBatisConfig {
/**
作用:
通過讀取application.properties檔案生成兩個資料來源(data1、data5)
使用以上生成的兩個資料來源構造動態資料來源dataSource
@Primary:指定在同一個介面有多個實現類可以注入的時候,預設選擇哪一個,而不是讓@Autowire註解報錯(一般用於多資料來源的情況下)
@Qualifier:指定名稱的注入,當一個介面有多個實現類的時候使用(在本例中,有兩個DataSource型別的例項,需要指定名稱注入)
@Bean:生成的bean例項的名稱是方法名(例如上邊的@Qualifier註解中使用的名稱是前邊兩個資料來源的方法名,而這兩個資料來源也是使用@Bean註解進行注入的)
通過動態資料來源構造SqlSessionFactory和事務管理器(如果不需要事務,後者可以去掉)
*
*/
@Autowired
private Environment env;
/**
* 建立資料來源(資料來源的名稱:方法名可以取為XXXDataSource(),XXX為資料庫名稱,該名稱也就是資料來源的名稱)
*/
@Bean
public DataSource myTestDbDataSource() throws Exception {
Properties props = new Properties();
props.put("driverClassName", env.getProperty("jdbc.driverClassName"));
props.put("url", env.getProperty("jdbc.url"));
props.put("username", env.getProperty("jdbc.username"));
props.put("password", env.getProperty("jdbc.password"));
return DruidDataSourceFactory.createDataSource(props);
}
@Bean
public DataSource myTestDb2DataSource() throws Exception {
Properties props = new Properties();
props.put("driverClassName", env.getProperty("jdbc2.driverClassName"));
props.put("url", env.getProperty("jdbc2.url"));
props.put("username", env.getProperty("jdbc2.username"));
props.put("password", env.getProperty("jdbc2.password"));
return DruidDataSourceFactory.createDataSource(props);
}
/**
* @Primary 該註解表示在同一個介面有多個實現類可以注入的時候,預設選擇哪一個,而不是讓@autowire註解報錯
* @Qualifier 根據名稱進行注入,通常是在具有相同的多個型別的例項的一個注入(例如有多個DataSource型別的例項)
*/
@Bean
@Primary
public DynamicDataSource dataSource(@Qualifier("myTestDbDataSource") DataSource myTestDbDataSource,
@Qualifier("myTestDb2DataSource") DataSource myTestDb2DataSource) {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DatabaseType.data, myTestDbDataSource);
targetDataSources.put(DatabaseType.data5, myTestDb2DataSource);
DynamicDataSource dataSource = new DynamicDataSource();
dataSource.setTargetDataSources(targetDataSources);// 該方法是AbstractRoutingDataSource的方法
// dataSource.setDefaultTargetDataSource(myTestDb2DataSource);// 預設的datasource設定為myTestDbDataSource
return dataSource;
}
/**
* 根據資料來源建立SqlSessionFactory
*/
@Bean(name="sqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(DynamicDataSource ds) throws Exception {
SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
fb.setDataSource(ds);// 指定資料來源(這個必須有,否則報錯)
// 下邊兩句僅僅用於*.xml檔案,如果整個持久層操作不需要使用到xml檔案的話(只用註解就可以搞定),則不加
fb.setTypeAliasesPackage(env.getProperty("mybatis.typeAliasesPackage"));// 指定基包
fb.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources(env.getProperty("mybatis.mapperLocations")));//
return fb.getObject();
}
/**
* 配置事務管理器
*/
@Bean
public DataSourceTransactionManager transactionManager(DynamicDataSource dataSource) throws Exception {
return new DataSourceTransactionManager(dataSource);
}
}
5.使用Spring 切入點動態切換資料來源 查資料到 data5資料來源 增刪改查到 data1資料來源
package com.company.test.base.config;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class DataSourceAspect {
/**
* 使用空方法定義切點表示式
*/
@Pointcut("execution(* com.company.test.dao.*.*(..))")
public void declareJointPointExpression() {
}
/**
* 使用定義切點表示式的方法進行切點表示式的引入
*/
@Before("declareJointPointExpression()")
//採用Mysql主從複製 讀寫分離 讀資料在data5 寫資料在data1資料庫
public void setDataSourceKey(JoinPoint point) {
String methodName = point.getSignature().getName(); // 獲取Method名稱
boolean flag = false;
flag = StringUtils.startsWithAny(methodName, "query", "find", "get");
if(flag){
DatabaseContextHolder.setDatabaseType(DatabaseType.data5);
}else{
DatabaseContextHolder.setDatabaseType(DatabaseType.data);
}
}
}
6.以Controller層方法名稱進行區分