天天看點

2--MyCAT中間件和ansible基礎三、Ansible介紹

一、Mycat

1)Mycat介紹

  • 在整個IT系統架構中,資料庫是非常重要,通常又是通路壓力較大的一個服務,除了在程式開發的本身做優化,如:SQL語句優化、代碼優化,資料庫的處理本身優化也是非常重要的。主從、熱備、分表分庫等都是系統發展遲早會遇到的技術問題問題。Mycat是一個廣受好評的資料庫中間件,已經在很多産品上進行使用了。
  • Mycat是一個開源的分布式資料庫系統,是一個實作了MySQL協定的伺服器,前端使用者可以把它看作是一個資料庫代理(類似于Mysql Proxy),用MySQL用戶端工具和指令行通路,而其後端可以用MySQL原生協定與多個MySQL伺服器通信,也可以用JDBC協定與大多數主流資料庫伺服器通信,其核心功能是分表分庫,即将一個大表水準分割為N個小表,存儲在後端MySQL伺服器裡或者其他資料庫裡。
  • Mycat發展到目前的版本,已經不是一個單純的MySQL代理了,它的後端可以支援MysQL、sQLServer、Oracle、DB2、PostgreSQL等主流資料庫,也支援MongoDB這種新型NoSQL方式的存儲,未來還會支援更多類型的存儲。而在最終使用者看來,無論是那種存儲方式,在MyCat裡,都是一個傳統的資料庫表,支援标準的SQL語句進行資料的操作,這樣一來,對前端業務系統來說,可以大幅降低開發難度,提升開發速度。

2)Mycat可以簡單概況為 

  • 一個徹底開源的,面向企業應用開發的大資料庫叢集
  • 支援事務、ACID、可以替代MySQL的加強版資料庫
  • 一個可以視為MySQL叢集的企業級資料庫,用來替代昂貴的Oracle叢集
  • 一個融合記憶體緩存技術、NoSQL技術、HDFS大資料的新型SQL Server
  • 結合傳統資料庫和新型分布式資料倉庫的新一代企業級資料庫産品
  • 一個新穎的資料庫中間件産品
Mycat官網: http://www.mycat.org.cn 

3)Mycat關鍵特性

  • 支援SQL92标準
  • 遵守MySQL原生協定,跨語言,跨平台,跨資料庫的通用中間件代理
  • 基于心跳的自動故障切換,支援讀寫分離,支援MySQL主從,以及galera cluster叢集支援Galera for MySQL叢集,Percona Cluster或者MariaDB cluster
  • 基于Nio實作,有效管理線程,高并發問題
  • 支援資料的多片自動路由與聚合,支援sum,count,max等常用的聚合函數,支援跨庫分頁
  • 支援單庫内部任意join,支援跨庫2表join,甚至基于caltlet的多表join
  • 支援通過全局表,ER關系的分片政策,實作了高效的多表join查詢
  • 支援多租戶方案
  • 支援分布式事務(弱xa)
  • 支援全局序列号,解決分布式下的主鍵生成問題
  • 分片規則豐富,插件化開發,易于擴充
  • 強大的web,指令行監控
  • 支援前端作為mysq通用代理,後端JDBC方式支援Oracle、DB2、SQL Server、mongodb、巨杉
  • 支援密碼加密
  • 支援服務降級
  • 支援IP白名單
  • 支援SQL黑名單、sql注入攻擊攔截
  • 支援分表(1.6)
  • ·叢集基于ZooKeeper管理,線上更新,擴容,智能優化,大資料處理(2.0開發版)

 4)為什麼要用MyCat

  • 這裡要先搞清楚Mycat和MySQL的差別(Mycat的核心作用)。我們可以把上層看作是對下層的抽象,例如作業系統是對各類計算機硬體的抽象。那麼我們什麼時候需要抽象?假如隻有一種硬體的時候,我們需要開發一個作業系統嗎?再比如一個項目隻需要一個人完成的時候不需要leader,但是當需要幾十人完成時,就應該有一個管理者,發揮溝通協調等作用,而這個管理者對于他的上層來說就是對項目組的抽象。
  • 同樣的,當我們的應用隻需要一台資料庫伺服器的時候我們并不需要Mycat,而如果你需要分庫甚至分表,這時候應用要面對很多個資料庫的時候,這個時候就需要對資料庫層做一個抽象,來管理這些資料庫,而最上面的應用隻需要面對一個資料庫層的抽象或者說資料庫中間件就好了,這就是Mycat的核心作用。是以可以這樣了解:資料庫是對底層存儲檔案的抽象,而Mycat是對資料庫的抽象。

5)Mycat工作原理

2--MyCAT中間件和ansible基礎三、Ansible介紹
  • Mycat的原理中最重要的一個動詞是"攔截"”,它攔截了使用者發送過來的SQL語句,首先對sQL語句做了一些特定的分析:如分片分析、路由分析、讀寫分離分析、緩存分析等,然後将此SQL發往後端的真實資料庫,并将傳回的結果做适當的處理,最終再傳回給使用者。

 6)Mycat應用場景

  • 單純的讀寫分離,此時配置最為簡單,支援讀寫分離,主從切換
  • 分表分庫,對于超過1000萬的表進行分片,最大支援1000億的單表分片
  • 多租戶應用,每個應用一個庫,但應用程式隻連接配接Mycat,進而不改造程式本身,實作多租戶化報表系統,借助于Mycat的分表能力,處理大規模報表的統計
  • 替代Hbase,分析大資料
  • 作為海量資料實時查詢的一種簡單有效方案,比如100億條頻繁查詢的記錄需要在3秒内查詢出來結果,除了基于主鍵的查詢,還可能存在範圍查詢或其他屬性查詢,此時Mycat可能是最簡單有效的選擇
  • Mycat長期路線圖
  • 強化分布式資料庫中間件的方面的功能,使之具備豐富的插件、強大的資料庫智能優化功能、全面的系統監控能力、以及友善的資料運維工具,實作線上資料擴容、遷移等進階功能
  • ·進一步挺進大資料計算領域,深度結合Spark Stream和Storm等分布式實時流引擎,能夠完成快速的巨表關聯、排序、分組聚合等OLAP方向的能力,并內建一些熱門常用的實時分析算法,讓工程師以及DBA們更容易用Mcat實作一些進階資料分析處理功能
  • 不斷強化Mycat開源社群的技術水準,吸引更多的IT技術專家,使得Mycat社群成為中國的
  • Apache,并将Mycat推到Apache基金會,成為國内頂尖開源項目,最終能夠讓一部分志願者成為專職的Mycat開發者,榮耀跟實力一起提升

 7)Mycat不适合的應用場景

  • 設計使用Mycat時有非分片字段查詢,請慎重使用Mycat,可以考慮放棄!
  • 設計使用Mycat時有分頁排序,請慎重使用Mycat,可以考慮放棄!
  • 設計使用Mycat時如果要進行表OIN操作,要確定兩個表的關聯字段具有相同的資料分布,否則請慎重使用Mycat,可以考慮放棄!
  • 設計使用Mycat時如果有分布式事務,得先看是否得保證事務得強一緻性,否則請慎重使用Mycat,可以考慮放棄!

8)MyCat的高可用性: 

需要注意:在生産環境中, Mycat節點最好使用雙節點,即雙機熱備環境,防止Mycat這一層出現單點故障.可以使用的高可用叢集方式有:
  • Keepalived+Mycat+Mysql
  • Keepalived+LVS+Mycat+Mysql
  • Keepalived+Haproxy+Mycat+Mysql

 9)Mycat安裝

1、安裝JDK
[[email protected] 22:52:21~]# yum -y insta1l java

[[email protected] 22:52:21~]# java -version
openjdk version "1.8.0_201"
           
2、安裝Mycat
[[email protected] 22:52:21~]# wget http://dl.mycat.org.cn/1.6.7.4/Mycat-server-1.6.7.4-release/Mycat-server-1.6.7.4-release-20200105164103-linux.tar.gz

[[email protected] 22:54:31~]# mkdir /data/software/ -p

[[email protected] 22:56:51~]# tar xvf Mycat-server-1.6.7.4-release-20200105164103-linux.tar.gz -C /data/software/

[[email protected] 22:57:25~]# cat > /etc/profile.d/mycat_home.sh<<EOF
MYCAT_HOME=/data/software/mycat
export PATH=\${PATH}:\${MYCAT_HOME}/bin
EOF

[[email protected] 23:57:30~]# source /etc/profile.d/mycat_home.sh
           
3、mycat安裝目錄結構:
  • bin mycat指令,啟動、重新開機、停止等
  • catlet catlet為Mycat的一個擴充功能
  • conf Mycat配置資訊,重點關注
  • lib Mycat引用的jar包,Mycat是java開發的
  • logs日志檔案,包括Mycat啟動的日志和運作的日志. version.txtmycat版本說明
4、logs目錄:
  • wrapper.log mycat啟動日志
  • mycatlog  mycat詳細工作日志
5、Mycat的配置檔案都在conf目錄裡面,這裡介紹幾個常用的檔案:
  • server.xml  Mycat軟體本身相關的配置檔案,設定賬号、參數等
  • schema.xml  Mycat對應的實體資料庫和資料庫表的配置,讀寫分離、高可用、分布式政策定制、節點控制
  •  rule.xml  Mycat分片(分庫分表)規則配置檔案,記錄分片規則清單、使用方法等
6、啟動和連接配接
[[email protected] 23:15:08~]# mycat start # 啟動

# 檢查啟動日志,确定啟動成功
[[email protected] 23:16:03~]# grep -w 'startup' /data/software/mycat/logs/wrapper.log

# 連接配接mycat:
[[email protected] 23:16:13~]# mysq1 -uroot -p123456 -h 127.0.0.1 -P8066
           

 10)MyCAT中間件服務實作讀寫分離

系統環境

cat /etc/redhat-release 
CentOS Linux release 8.3.2011
           

(1)架構圖如下

2--MyCAT中間件和ansible基礎三、Ansible介紹

 (2)搭建MySQL主從

1、主MySQL配置(IP:192.168.64.10)
[[email protected] 22:46:42~]# cat /etc/my.cnf

[mysqld]
server-id=10
log_bin

[[email protected] 22:46:42~]# systemctl enable mariadb && systemctl restart mariadb

[[email protected] 22:48:39~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 9
Server version: 10.3.28-MariaDB-log MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> show master status;
+--------------------+----------+--------------+------------------+
| File               | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+--------------------+----------+--------------+------------------+
| mariadb-bin.000001 |      330 |              |                  |
+--------------------+----------+--------------+------------------+
1 row in set (0.000 sec)

MariaDB [(none)]> grant all on *.* to [email protected]'%' identified by "123456";
Query OK, 0 rows affected (0.001 sec)

MariaDB [(none)]> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> source hellodb_innodb.sql;  # 導入資料,如果沒有,自己随便弄點

MariaDB [mysql]> show databases;
+--------------------+
| Database           |
+--------------------+
| hellodb            |
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+
5 rows in set (0.001 sec)

MariaDB [mysql]> use hellodb;
Database changed

MariaDB [hellodb]> show tables;
+-------------------+
| Tables_in_hellodb |
+-------------------+
| classes           |
| coc               |
| courses           |
| scores            |
| students          |
| teachers          |
| toc               |
+-------------------+
7 rows in set (0.000 sec)

MariaDB [hellodb]> set global general_log=ON;  # 開啟記錄檔記錄,隻是利于檢查主從是否生效
Query OK, 0 rows affected (0.000 sec)

MariaDB [hellodb]> show variables like 'gen%';
+------------------+------------+
| Variable_name    | Value      |
+------------------+------------+
| general_log      | ON         |
| general_log_file | master.log |
+------------------+------------+
2 rows in set (0.001 sec)

MariaDB [hellodb]> 
           

2、從MySQL配置(IP:192.168.64.12)

CHANGE MASTER To MASTER_HOST='192.168.64.10', MASTER_USER='slave', MASTER_PASSwORD='123456', MASTER_LOG_FILE='mariadb-bin.000001', MASTER_LOG_POS=330;

[[email protected] 10:51:01~]# cat /etc/my.cnf
[mysqld]
server-id=12

[[email protected] 10:51:09~]# systemctl enable mariadb && systemctl restart mariadb

[[email protected] 10:51:31~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 8
Server version: 10.3.28-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> CHANGE MASTER To
    -> MASTER_HOST='192.168.64.10',
    -> MASTER_USER='slave', 
    -> MASTER_PASSwORD='123456',
    -> MASTER_LOG_FILE='mariadb-bin.000001',
    -> MASTER_LOG_POS=330;

MariaDB [(none)]> start slave;
Query OK, 0 rows affected (0.001 sec)

MariaDB [(none)]> SHOW SLAVE STATUS\G
*************************** 1. row ***************************
                Slave_IO_State: Waiting for master to send event
                   Master_Host: 192.168.64.10
                   Master_User: slave
                   Master_Port: 3306
                 Connect_Retry: 60
               Master_Log_File: mariadb-bin.000001
           Read_Master_Log_Pos: 957
                Relay_Log_File: mariadb-relay-bin.000002
                 Relay_Log_Pos: 1184
         Relay_Master_Log_File: mariadb-bin.000001
              Slave_IO_Running: Yes
             Slave_SQL_Running: Yes
               Replicate_Do_DB: 
           Replicate_Ignore_DB: 
            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: 957
               Relay_Log_Space: 1495
               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: 10
                Master_SSL_Crl: 
            Master_SSL_Crlpath: 
                    Using_Gtid: No
                   Gtid_IO_Pos: 
       Replicate_Do_Domain_Ids: 
   Replicate_Ignore_Domain_Ids: 
                 Parallel_Mode: conservative
                     SQL_Delay: 0
           SQL_Remaining_Delay: NULL
       Slave_SQL_Running_State: Slave has read all relay log; waiting for the slave I/O thread to update it
              Slave_DDL_Groups: 4
Slave_Non_Transactional_Groups: 0
    Slave_Transactional_Groups: 0
1 row in set (0.000 sec)


MariaDB [hellodb]> set global general_log=ON;   # 開啟記錄檔記錄,隻是利于檢查主從是否生效
Query OK, 0 rows affected (0.000 sec)

MariaDB [hellodb]> show variables like 'gen%';
+------------------+-----------+
| Variable_name    | Value     |
+------------------+-----------+
| general_log      | ON        |
| general_log_file | slave.log |
+------------------+-----------+
2 rows in set (0.001 sec)

MariaDB [hellodb]> 
           

 (3)安裝 mycat(192.168.64.11)

 1、安裝依賴環境java
yum -y install java
           
2、安裝mycat
[[email protected] 22:52:21~]# wget http://dl.mycat.org.cn/1.6.7.4/Mycat-server-1.6.7.4-release/Mycat-server-1.6.7.4-release-20200105164103-linux.tar.gz

[[email protected] 22:54:31~]# mkdir /data/software/ -p

[[email protected]  22:56:51~]# tar xvf Mycat-server-1.6.7.4-release-20200105164103-linux.tar.gz -C /data/software/

[[email protected] 22:57:25~]# cat > /etc/profile.d/mycat_home.sh<<EOF
MYCAT_HOME=/data/software/mycat
export PATH=\${PATH}:\${MYCAT_HOME}/bin
EOF

[[email protected]  22:57:30~]# source /etc/profile.d/mycat_home.sh

[[email protected] 22:57:32~]# mycat
Usage: /data/software/mycat/bin/mycat { console | start | stop | restart | status | dump }
           
 3、修改schema.xml配置檔案
<!DOCTYPE mycat:schema SYSTEM "schema. dtd">
<mycat:schema xmlns:mycat="http://io.mycat/">

    <!-- db_name_1是命名辨別的第一個資料庫,名字自己取,其中hellodb表示後端伺服器實際的資料庫名稱 -->
    <schema name="TESTDB" checkSQLschema="fa1se" sqlMaxLimit="100" dataNode="db_name_1"></schema>
    <dataNode name="db_name_1" dataHost="mysql_host_1" database="hellodb" /> 

    <!-- mysql_host_1是命名辨別的第一個資料庫連接配接IP位址,名字自己取 -->
    <dataHost name="mysql_host_1" maxCon="1000" minCon="10" balance="1" writeType="0" dbType="mysql" dbDriver="native" switchType="1" slaveThreshold="100">

    <!-- 檢查後端MySQL是否還存活,心跳檢查,也是配置主從 -->
    <heartbeat>select user()</heartbeat>
    <writeHost host="host1" url="192.168.64.10:3306" user="slave" password="123456">
    <readHost host="host2" url="192.168.64.12:3306" user="slave" password="123456"/>

</writeHost>
</dataHost>
</mycat:schema>
           
4、修改schema.xml配置檔案
[[email protected] 21:10:16/data/software/mycat/conf]# cat server.xml 

。。。略

        <user name="root" defaultAccount="true">
                <property name="password">123456</property>
                <property name="schemas">TESTDB</property>
                <property name="defaultSchema">TESTDB</property>
                <!--No MyCAT Database selected 錯誤前會嘗試使用該schema作為schema,不設定則為null,報錯 -->

。。。略
           
5、啟動mycat
[[email protected] 09:41:49/data/software/mycat/conf]# mycat start

[[email protected] 09:42:10/data/software/mycat/conf]# grep -w 'startup' /data/software/mycat/logs/wrapper.log
INFO   | jvm 1    | 2021/08/22 09:41:09 | MyCAT Server startup successfully. see logs in logs/mycat.log

[[email protected] 09:45:45/data/software/mycat/conf]# netstat -untpl | grep 8066
tcp6       0      0 :::8066                 :::*                    LISTEN      29103/java
           
6、模拟客服端連接配接mycat通路後端mysql讀寫分離(進行讀操作)
[[email protected] 21:45:03~]# mysql -uroot -p123456 -h192.168.64.11 -P8066
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.6.29-mycat-1.6.7.4-release-20200105164103 MyCat Server (OpenCloudDB)

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MySQL [(none)]> show databases;
+----------+
| DATABASE |
+----------+
| TESTDB   |
+----------+
1 row in set (0.002 sec)

MySQL [(none)]> use TESTDB;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MySQL [TESTDB]> show tables;
+-------------------+
| Tables_in_hellodb |
+-------------------+
| classes           |
| coc               |
| courses           |
| scores            |
| students          |
| teachers          |
| toc               |
+-------------------+
7 rows in set (0.003 sec)

MySQL [TESTDB]>
           

6、檢查結果,剛剛上面一直操作的是讀,我們來看看結果

在mysql主伺服器(master:192.168.64.10)上執行:show processlist;

并沒有看到客服端連接配接過來的資訊

2--MyCAT中間件和ansible基礎三、Ansible介紹
檢查日志 :/var/lib/mysql 
2--MyCAT中間件和ansible基礎三、Ansible介紹

在mysql從伺服器(slave:192.168.64.12)上執行:show processlist;

我們是能看到客服端連接配接過來的資訊

2--MyCAT中間件和ansible基礎三、Ansible介紹
檢查日志 :/var/lib/mysql
2--MyCAT中間件和ansible基礎三、Ansible介紹
 7、模拟客服端連接配接mycat通路後端mysql讀寫分離(進行寫操作)
MySQL [TESTDB]> insert teachers(name,age,gender)values('mo',18,'M');
Query OK, 1 row affected (0.023 sec)

MySQL [TESTDB]> 
           

 8、檢查結果,剛剛上面執行了一條寫操作,我們來看看結果

在mysql主伺服器(master:192.168.64.10)上檢查日志:

2--MyCAT中間件和ansible基礎三、Ansible介紹

在mysql從伺服器(master:192.168.64.12)上檢查日志: 

因為會從主伺服器上複制資料過來,是以是存在着有記錄的

2--MyCAT中間件和ansible基礎三、Ansible介紹

 二、MHA實作MySQL的高可用性

1)資源包下載下傳

 manager包
[[email protected] 10:39:17/data/software]# wget https://github.com/yoshinorim/mha4mysql-manager/releases/download/v0.58/mha4mysql-manager-0.58-0.el7.centos.noarch.rpm
           
node包
[[email protected] 10:39:24/data/software]# wget  https://github.com/yoshinorim/mha4mysql-node/releases/download/v0.58/mha4mysql-node-0.58-0.el7.centos.noarch.rpm
           

2)部署架構圖

2--MyCAT中間件和ansible基礎三、Ansible介紹

 3)部署環境,由于manager隻能用centos7,是以環境全部用centos7,支援MySQL5.7

  • 說明: mha4mysql-manager-0.56-0.el6.noarch.rpm 不支援CentOS 8,隻支援CentOS7以下版本
  • 說明: mha4mysql-manager-0.58-0.el7.centos.noarch.rpm ,支援MySQL 5.7 ,但和CentOs8版本上的Mariadb -10.3.17不相容

 MySQL5.7百度網盤位址下載下傳

連結:https://pan.baidu.com/s/12JXp8r-NU2yzaHSa4d1BSg 

提取碼:cmg7

1、在mha(192.168.64.10)的伺服器上安裝mha4mysql-manager和mha4mysql-node
# 先更新epel源
[[email protected]_192.168.64.10 13:13:05~]# yum install epel-release -y

# 下載下傳所需要的rpm包
[[email protected]_192.168.64.10 13:13:15~]# wget https://github.com/yoshinorim/mha4mysql-manager/releases/download/v0.58/mha4mysql-manager-0.58-0.el7.centos.noarch.rpm

[[email protected]_192.168.64.10 13:13:25~]# wget  https://github.com/yoshinorim/mha4mysql-node/releases/download/v0.58/mha4mysql-node-0.58-0.el7.centos.noarch.rpm

# 安裝
[[email protected]_192.168.64.10 13:14:43~]# yum -y install mha4mysql-*
           
2、其他三個節點(master、slave1、slave2)上安裝mha4mysql-node
[[email protected]_192.168.64.11 13:13:18~]# yum install epel-release -y

[[email protected]_192.168.64.11 13:13:25~]# wget https://github.com/yoshinorim/mha4mysql-node/releases/download/v0.58/mha4mysql-node-0.58-0.el7.centos.noarch.rpm

[[email protected]_192.168.64.11 13:13:48~]# yum -y install mha4mysql-node-0.58-0.el7.centos.noarch.rpm
           
3、建立所有節點無密登入
[[email protected]_192.168.64.10 13:03:27~]# cat /etc/hosts
192.168.64.10 mha
192.168.64.11 master
192.168.64.12 slave1
192.168.64.13 slave2

[[email protected]_192.168.64.10 13:03:30~]# ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:JnhuOb7fyIenPTc7gDPWeOjowuh7JKibhrPahkJR/wU [email protected]
The key's randomart image is:
+---[RSA 2048]----+
|                 |
|   .   E         |
|  . .   .        |
| .   o   .       |
| .. . + S=       |
|... .o =B +      |
|+. =  =+ = .     |
|*+o +o.oo++ +    |
|O*+o o+o=+oo.+   |
+----[SHA256]-----+

[[email protected]_192.168.64.10 13:04:31~]# scp -r .ssh master:/root/
The authenticity of host 'master (192.168.64.11)' can't be established.
ECDSA key fingerprint is SHA256:ZWVQ5th7iynhNPKZXujWK5xHRER/eSMTPlSAa5n2n1k.
ECDSA key fingerprint is MD5:2a:b9:ce:23:c7:86:74:c5:9a:75:31:20:bf:80:9e:47.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'master,192.168.64.11' (ECDSA) to the list of known hosts.
[email protected]'s password: 
id_rsa                                                                                     100% 1675     1.1MB/s   00:00    
id_rsa.pub                                                                                 100%  390   440.3KB/s   00:00    
known_hosts                                                                                100%  361   372.8KB/s   00:00    
authorized_keys                                                                            100%  390   393.8KB/s   00:00    
[[email protected]_192.168.64.10 13:04:47~]# scp -r .ssh slave1:/root/
The authenticity of host 'slave1 (192.168.64.12)' can't be established.
ECDSA key fingerprint is SHA256:ZWVQ5th7iynhNPKZXujWK5xHRER/eSMTPlSAa5n2n1k.
ECDSA key fingerprint is MD5:2a:b9:ce:23:c7:86:74:c5:9a:75:31:20:bf:80:9e:47.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'slave1,192.168.64.12' (ECDSA) to the list of known hosts.
[email protected]'s password: 
id_rsa                                                                                     100% 1675   920.2KB/s   00:00    
id_rsa.pub                                                                                 100%  390   412.3KB/s   00:00    
known_hosts                                                                                100%  543   987.3KB/s   00:00    
authorized_keys                                                                            100%  390   741.8KB/s   00:00    
[[email protected]_192.168.64.10 13:04:56~]# scp -r .ssh slave2:/root/
The authenticity of host 'slave2 (192.168.64.13)' can't be established.
ECDSA key fingerprint is SHA256:ZWVQ5th7iynhNPKZXujWK5xHRER/eSMTPlSAa5n2n1k.
ECDSA key fingerprint is MD5:2a:b9:ce:23:c7:86:74:c5:9a:75:31:20:bf:80:9e:47.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'slave2,192.168.64.13' (ECDSA) to the list of known hosts.
[email protected]'s password: 
id_rsa                                                                                     100% 1675   864.5KB/s   00:00    
id_rsa.pub                                                                                 100%  390   168.5KB/s   00:00    
known_hosts                                                                                100%  725     1.0MB/s   00:00    
authorized_keys                                                                            100%  390   782.2KB/s   00:00    
[[email protected]_192.168.64.10 13:05:03~]# 
           
4、在管理節點(mha:192.168.64.10)建立配置檔案,注意:複制到配置檔案裡要把注釋資訊删掉,不然會報錯
[[email protected]_192.168.64.10 19:26:07~]# cat /etc/mastermha/app1.cnf
[server default]
user=mhauser  # 用于遠端連接配接MySQL所有節點的使用者,需要有管理者的權限
password=123456
manager_workdir=/data/mastermha/app1/   # 目錄會自動生成,無需手動建立
manager_log=/data/mastermha/app1/manager.log
ssh_user=root  # 用于實作遠端ssh基于KEY的連接配接,通路二進制日志
repl_user=slave  # 主從複制的使用者資訊
repl_password=123456
ping_interval=1    # 健康性檢查的時間間隔
master_ip_failover_script=/usr/local/bin/master_ip_failover  # 切換VIP的per1腳本
report_script=/usr/local/bin/sendmail.sh   # 郵件通知,告警用的
check_repl_delay=0   # 預設如果slave中從庫落後主庫relaylog超過100M,主庫不會選擇這個從庫為新的master,因為這個從庫進行恢複需要很長的時間.通過這個參數,mha觸發主從切換的時候會忽略複制的延時,通過check_repl_delay=0這個參數,mha觸發主從切換時會忽略複制的延時,對于設定candidate_master=1的從庫非常有用,這樣確定這個從庫一定能成為最新的master
master_binlog_dir=/data/mysq1/   # 指定二進制日志存放的目錄,mha4mysq1-manager-0.58必須指定,之前版本不需要指定

[server1]
hostname=192.168.64.11
candidate_master=1

[server2]
hostname=192.168.64.12
candidate_master=1   # 設定為優先候選master,即使不是叢集中事件最新的s1ave,也會優先當master

[server3]
hostname=192.168.64.13
           
5、郵件通知腳本(隻在mha安裝)
[[email protected]_192.168.64.10 19:28:39~]# cat /usr/local/bin/sendmail.sh
echo 'MySQL is down' | mail -s 'MHA warning' [email protected]
[[email protected]_192.168.64.10 19:28:45~]# chmod +x /usr/local/bin/sendmail.sh
           

6、切換VIP的per1腳本(隻在mha安裝)

來源位址:原文連結:https://blog.csdn.net/shm19990131/article/details/107423239

[[email protected]_192.168.64.10 19:30:13~]# cat /usr/local/bin/master_ip_failover
#!/usr/bin/env perl

#  Copyright (C) 2011 DeNA Co.,Ltd.
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#  Foundation, Inc.,
#  51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

## Note: This is a sample script and is not complete. Modify the script based on your environment.

use strict;
use warnings FATAL => 'all';

use Getopt::Long;
use MHA::DBHelper;

my (
  $command,        $ssh_user,         $orig_master_host,
  $orig_master_ip, $orig_master_port, $new_master_host,
  $new_master_ip,  $new_master_port,  $new_master_user,
  $new_master_password
);
my $vip = '192.168.64.100/24';  # 設定virtual IP
my $gateway = '192.168.64.2';   # 網卡gateway IP
my $interface = 'ens32';        # 指定VIP所在網卡
my $key = "1";
my $ssh_start_vip = "/sbin/ifconfig $interface:$key Svip;/sbin/arping -I $interface -c 3 -s $vip $gateway >/dev/null 2>&1";
my $ssh_stop_vip = "/sbin/ifconfig $interface:$key down";

GetOptions(
  'command=s'             => \$command,
  'ssh_user=s'            => \$ssh_user,
  'orig_master_host=s'    => \$orig_master_host,
  'orig_master_ip=s'      => \$orig_master_ip,
  'orig_master_port=i'    => \$orig_master_port,
  'new_master_host=s'     => \$new_master_host,
  'new_master_ip=s'       => \$new_master_ip,
  'new_master_port=i'     => \$new_master_port,
  'new_master_user=s'     => \$new_master_user,
  'new_master_password=s' => \$new_master_password,
);

exit &main();

sub main {
  if ( $command eq "stop" || $command eq "stopssh" ) {

    # $orig_master_host, $orig_master_ip, $orig_master_port are passed.
    # If you manage master ip address at global catalog database,
    # invalidate orig_master_ip here.
    my $exit_code = 1;
    eval {

      # updating global catalog, etc
      $exit_code = 0;
    };
    if ([email protected]) {
      warn "Got Error: [email protected]\n";
      exit $exit_code;
    }
    exit $exit_code;
  }
    elsif ( $command eq "start" ) {

        # all arguments are passed.
        # If you manage master ip address at global catalog database,
        # activate new_master_ip here.
        # You can also grant write access (create user, set read_only=0, etc) here.
        my $exit_code = 10;
        eval {
            print "Enabling the VIP - $vip on the new master - $new_master_host \n";
            &start_vip();
            &stop_vip();
            $exit_code = 0;
        };
        if ([email protected]) {
            warn [email protected];
            exit $exit_code;
        }
        exit $exit_code;
    }
    elsif ( $command eq "status" ) {
        print "Checking the Status of the script.. OK \n";
        `ssh $ssh_user\@$orig_master_host \" $ssh_start_vip \"`;
        exit 0;
    }
    else {
        &usage();
        exit 1;
    }
}


sub start_vip() {
    `ssh $ssh_user\@$new_master_host \" $ssh_start_vip \"`;
}
# A simple system call that disable the VIP on the old_master 
sub stop_vip() {
   `ssh $ssh_user\@$orig_master_host \" $ssh_stop_vip \"`;
}


sub usage {
  print
"Usage: master_ip_failover --command=start|stop|stopssh|status --orig_master_host=host --orig_master_ip=ip --orig_master_port=port --new_master_host=host --new_master_ip=ip --new_master_port=port\n";
}

[[email protected]_192.168.64.10 21:22:41~]# chmod +x /usr/local/bin/master_ip_failover
           
7、安裝郵件服務(隻在mha安裝)
[[email protected]_192.168.64.10 22:23:41~]# yum -y install  s-nail

[[email protected]_192.168.64.10 22:27:57~]# cat /etc/mail.rc
set from [email protected]
set smtp=smtp.qq.com
set [email protected]
set smtp-auth-password=123456789  # 授權碼,不是QQ密碼

# 測試
[[email protected]_192.168.64.10 22:31:23~]# sh /usr/local/bin/sendmail.sh
           
2--MyCAT中間件和ansible基礎三、Ansible介紹
8、在master、slave1、slave2安裝mysql5.7
yum -y install numactl gcc gcc-c++
groupadd mysql
useradd -r -s /sbin/nologin -g mysql mysql
tar zxf mysql-5.7.27-linux-glibc2.12-x86_64.tar.gz
mkdir -p /data/software
mv mysql-5.7.27-linux-glibc2.12-x86_64 /data/software/mysql
cd /data/software/mysql
mkdir tmp run log data
touch log/mysql.log
chown mysql:mysql  ../mysql/ -R

cat > /etc/my.cnf <<EOF
根據master、slave1、slave2來配置,詳細請看下面
EOF

source /etc/profile
chkconfig --add mysql
chkconfig --level 345 mysql on

service mysql start

source /etc/profile

mysql_pass=$(awk -F 'localhost: ' '$2!="" {print $2}' /data/software/mysql/log/mysql.log)

export MYSQL_PWD=${mysql_pass}

grant_sql="
set password=password('123456');
flush privileges;"

mysql -uroot -e "${grant_sql}" --connect-expired-password
           
 9、master的mysql配置
[[email protected]_192.168.64.11 22:53:02~]# cat /etc/my.cnf
[client]
port        = 3306
socket=/data/software/mysql/tmp/mysql.sock

[mysqld]
port        = 3306
socket=/data/software/mysql/tmp/mysql.sock
log-error=/data/software/mysql/log/mysql.log
pid-file=/data/software/mysql/tmp/mysql.pid
datadir=/data/software/mysql/data
skip-external-locking
key_buffer_size = 64M
max_allowed_packet = 1M
table_open_cache = 256
sort_buffer_size = 1M
net_buffer_length = 8K
read_buffer_size = 1M
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 16M
thread_cache_size = 32
query_cache_size = 32M
tmp_table_size = 64M
performance_schema_max_table_instances = 2000

explicit_defaults_for_timestamp = true
max_connections = 500
max_connect_errors = 100
open_files_limit = 65535

log-bin=mysql-bin
binlog_format=mixed
server-id   = 11     # 每台伺服器上的id是不同的,以IP結尾做ID,slave1為12,slave2為13
skip_name_resolve=1  # 禁止反向解析
general_log
expire_logs_days = 10
early-plugin-load = ""

default_storage_engine = InnoDB
innodb_file_per_table = 1
innodb_data_home_dir = /data/software/mysql/data
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = /data/software/mysql/data
innodb_buffer_pool_size = 256M
innodb_log_file_size = 64M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit = 1
innodb_lock_wait_timeout = 50

[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash

[myisamchk]
key_buffer_size = 64M
sort_buffer_size = 1M
read_buffer_size = 1M
write_buffer_size = 2M

[mysqlhotcopy]
interactive-timeout

[mysqld_safe]
log-error=/data/software/mysql/log/mysql.log
pid-file=/data/software/mysql/tmp/mysql.pid
           
10、master綁定網卡192.168.64.100的IP位址作為VIP位址:
[[email protected]_192.168.64.11 07:05:28~]# ifconfig ens32:1 192.168.64.100/24
           
11、slave1配置
[[email protected]_192.168.64.12 22:58:09~]# cat /etc/my.cnf
[client]
port        = 3306
socket=/data/software/mysql/tmp/mysql.sock

[mysqld]
port        = 3306
socket=/data/software/mysql/tmp/mysql.sock
log-error=/data/software/mysql/log/mysql.log
pid-file=/data/software/mysql/tmp/mysql.pid
datadir=/data/software/mysql/data
skip-external-locking
key_buffer_size = 64M
max_allowed_packet = 1M
table_open_cache = 256
sort_buffer_size = 1M
net_buffer_length = 8K
read_buffer_size = 1M
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 16M
thread_cache_size = 32
query_cache_size = 32M
tmp_table_size = 64M
performance_schema_max_table_instances = 2000

explicit_defaults_for_timestamp = true
max_connections = 500
max_connect_errors = 100
open_files_limit = 65535

log-bin=mysql-bin
binlog_format=mixed
server-id   = 12
read-only
relay_log_purge=0
skip_name_resolve=1  # 禁止反向解析
expire_logs_days = 10
early-plugin-load = ""

default_storage_engine = InnoDB
innodb_file_per_table = 1
innodb_data_home_dir = /data/software/mysql/data
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = /data/software/mysql/data
innodb_buffer_pool_size = 256M
innodb_log_file_size = 64M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit = 1
innodb_lock_wait_timeout = 50

[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash

[myisamchk]
key_buffer_size = 64M
sort_buffer_size = 1M
read_buffer_size = 1M
write_buffer_size = 2M

[mysqlhotcopy]
interactive-timeout

[mysqld_safe]
log-error=/data/software/mysql/log/mysql.log
pid-file=/data/software/mysql/tmp/mysql.pid
           
12、slave2配置
[[email protected]_192.168.64.13 22:58:31~]# cat /etc/my.cnf
[client]
port        = 3306
socket=/data/software/mysql/tmp/mysql.sock

[mysqld]
port        = 3306
socket=/data/software/mysql/tmp/mysql.sock
log-error=/data/software/mysql/log/mysql.log
pid-file=/data/software/mysql/tmp/mysql.pid
datadir=/data/software/mysql/data
skip-external-locking
key_buffer_size = 64M
max_allowed_packet = 1M
table_open_cache = 256
sort_buffer_size = 1M
net_buffer_length = 8K
read_buffer_size = 1M
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 16M
thread_cache_size = 32
query_cache_size = 32M
tmp_table_size = 64M
performance_schema_max_table_instances = 2000

explicit_defaults_for_timestamp = true
max_connections = 500
max_connect_errors = 100
open_files_limit = 65535

log-bin=mysql-bin
binlog_format=mixed
server-id   = 13
read-only
relay_log_purge=0
skip_name_resolve=1  # 禁止反向解析
general_log
expire_logs_days = 10
early-plugin-load = ""

default_storage_engine = InnoDB
innodb_file_per_table = 1
innodb_data_home_dir = /data/software/mysql/data
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = /data/software/mysql/data
innodb_buffer_pool_size = 256M
innodb_log_file_size = 64M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit = 1
innodb_lock_wait_timeout = 50

[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash

[myisamchk]
key_buffer_size = 64M
sort_buffer_size = 1M
read_buffer_size = 1M
write_buffer_size = 2M

[mysqlhotcopy]
interactive-timeout

[mysqld_safe]
log-error=/data/software/mysql/log/mysql.log
pid-file=/data/software/mysql/tmp/mysql.pid
           
13、master建立賬号和導入資料
[[email protected]_192.168.64.11 23:03:12~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 9
Server version: 10.3.31-MariaDB-log MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> show master status;
+-------------------+----------+--------------+------------------+
| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+-------------------+----------+--------------+------------------+
| master-bin.000001 |      329 |              |                  |
+-------------------+----------+--------------+------------------+
1 row in set (0.001 sec)

MariaDB [(none)]> grant all on *.* to [email protected]'%' identified by "123456";
Query OK, 0 rows affected (0.001 sec)

MariaDB [hellodb]> grant all on *.* to [email protected]'%' identified by "123456";
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> source hellodb_innodb.sql;
           
14、slave1、slave2執行配置從節點操作
CHANGE MASTER To 
MASTER_HOST='192.168.64.11', 
MASTER_USER='slave', 
MASTER_PASSwORD='123456', 
MASTER_LOG_FILE='master-bin.000001', 
MASTER_LOG_POS=329;
           
[[email protected]_192.168.64.12 23:03:24~]# mysql
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 9
Server version: 10.3.31-MariaDB-log MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> CHANGE MASTER To 
    -> MASTER_HOST='192.168.64.11', 
    -> MASTER_USER='slave', 
    -> MASTER_PASSwORD='123456', 
    -> MASTER_LOG_FILE='master-bin.000001', 
    -> MASTER_LOG_POS=329;
Query OK, 0 rows affected (0.006 sec)

MariaDB [(none)]> start slave;
Query OK, 0 rows affected (0.001 sec)

MariaDB [(none)]> show slave status\G
*************************** 1. row ***************************
                Slave_IO_State: Waiting for master to send event
                   Master_Host: 192.168.64.11
                   Master_User: slave
                   Master_Port: 3306
                 Connect_Retry: 60
               Master_Log_File: master-bin.000001
           Read_Master_Log_Pos: 9551
                Relay_Log_File: slave1-relay-bin.000002
                 Relay_Log_Pos: 9778
         Relay_Master_Log_File: master-bin.000001
              Slave_IO_Running: Yes
             Slave_SQL_Running: Yes


MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| hellodb            |
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+
5 rows in set (0.000 sec)

MariaDB [(none)]> use hellodb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [hellodb]> show tables;
+-------------------+
| Tables_in_hellodb |
+-------------------+
| classes           |
| coc               |
| courses           |
| scores            |
| students          |
| teachers          |
| toc               |
+-------------------+
7 rows in set (0.000 sec)

MariaDB [hellodb]>
           

15、檢查ssh配置連通是否正常,

提示   All SSH connection tests passed successfully.   則是正常的:

[[email protected]_192.168.64.10 23:41:49~]# masterha_check_ssh --conf=/etc/mastermha/app1.cnf
Sun Aug 22 23:41:52 2021 - [warning] Global configuration file /etc/masterha_default.cnf not found. Skipping.
Sun Aug 22 23:41:52 2021 - [info] Reading application default configuration from /etc/mastermha/app1.cnf..
Sun Aug 22 23:41:52 2021 - [info] Reading server configuration from /etc/mastermha/app1.cnf..
Sun Aug 22 23:41:52 2021 - [info] Starting SSH connection tests..
Sun Aug 22 23:41:53 2021 - [debug] 
Sun Aug 22 23:41:52 2021 - [debug]  Connecting via SSH from [email protected](192.168.64.11:22) to [email protected](192.168.64.12:22)..
Sun Aug 22 23:41:52 2021 - [debug]   ok.
Sun Aug 22 23:41:52 2021 - [debug]  Connecting via SSH from [email protected](192.168.64.11:22) to [email protected](192.168.64.13:22)..
Sun Aug 22 23:41:52 2021 - [debug]   ok.
Sun Aug 22 23:41:53 2021 - [debug] 
Sun Aug 22 23:41:52 2021 - [debug]  Connecting via SSH from [email protected](192.168.64.12:22) to [email protected](192.168.64.11:22)..
Sun Aug 22 23:41:52 2021 - [debug]   ok.
Sun Aug 22 23:41:52 2021 - [debug]  Connecting via SSH from [email protected](192.168.64.12:22) to [email protected](192.168.64.13:22)..
Sun Aug 22 23:41:53 2021 - [debug]   ok.
Sun Aug 22 23:41:54 2021 - [debug] 
Sun Aug 22 23:41:53 2021 - [debug]  Connecting via SSH from [email protected](192.168.64.13:22) to [email protected](192.168.64.11:22)..
Sun Aug 22 23:41:53 2021 - [debug]   ok.
Sun Aug 22 23:41:53 2021 - [debug]  Connecting via SSH from [email protected](192.168.64.13:22) to [email protected](192.168.64.12:22)..
Sun Aug 22 23:41:53 2021 - [debug]   ok.
Sun Aug 22 23:41:54 2021 - [info] All SSH connection tests passed successfully.
           

16、檢查MySQL配置連通是否正常

最後提示   MySQL Replication Health is OK.   則是正常的,如果提示  NOT OK!  則不正常。

[[email protected]_192.168.64.10 21:57:09/etc/mastermha]# masterha_check_repl --conf=/etc/mastermha/app1.cnf 
Tue Aug 24 21:57:11 2021 - [warning] Global configuration file /etc/masterha_default.cnf not found. Skipping.
Tue Aug 24 21:57:11 2021 - [info] Reading application default configuration from /etc/mastermha/app1.cnf..
Tue Aug 24 21:57:11 2021 - [info] Reading server configuration from /etc/mastermha/app1.cnf..
Tue Aug 24 21:57:11 2021 - [info] MHA::MasterMonitor version 0.58.
Tue Aug 24 21:57:12 2021 - [info] GTID failover mode = 0
Tue Aug 24 21:57:12 2021 - [info] Dead Servers:
Tue Aug 24 21:57:12 2021 - [info] Alive Servers:
Tue Aug 24 21:57:12 2021 - [info]   192.168.64.11(192.168.64.11:3306)
Tue Aug 24 21:57:12 2021 - [info]   192.168.64.12(192.168.64.12:3306)
Tue Aug 24 21:57:12 2021 - [info]   192.168.64.13(192.168.64.13:3306)
Tue Aug 24 21:57:12 2021 - [info] Alive Slaves:
Tue Aug 24 21:57:12 2021 - [info]   192.168.64.12(192.168.64.12:3306)  Version=5.7.27-log (oldest major version between slaves) log-bin:enabled
Tue Aug 24 21:57:12 2021 - [info]     Replicating from 192.168.64.11(192.168.64.11:3306)
Tue Aug 24 21:57:12 2021 - [info]     Primary candidate for the new Master (candidate_master is set)
Tue Aug 24 21:57:12 2021 - [info]   192.168.64.13(192.168.64.13:3306)  Version=5.7.27-log (oldest major version between slaves) log-bin:enabled
Tue Aug 24 21:57:12 2021 - [info]     Replicating from 192.168.64.11(192.168.64.11:3306)
Tue Aug 24 21:57:12 2021 - [info] Current Alive Master: 192.168.64.11(192.168.64.11:3306)
Tue Aug 24 21:57:12 2021 - [info] Checking slave configurations..
Tue Aug 24 21:57:12 2021 - [info] Checking replication filtering settings..
Tue Aug 24 21:57:12 2021 - [info]  binlog_do_db= , binlog_ignore_db= 
Tue Aug 24 21:57:12 2021 - [info]  Replication filtering check ok.
Tue Aug 24 21:57:12 2021 - [info] GTID (with auto-pos) is not supported
Tue Aug 24 21:57:12 2021 - [info] Starting SSH connection tests..
Tue Aug 24 21:57:15 2021 - [info] All SSH connection tests passed successfully.
Tue Aug 24 21:57:15 2021 - [info] Checking MHA Node version..
Tue Aug 24 21:57:15 2021 - [info]  Version check ok.
Tue Aug 24 21:57:15 2021 - [info] Checking SSH publickey authentication settings on the current master..
Tue Aug 24 21:57:15 2021 - [info] HealthCheck: SSH to 192.168.64.11 is reachable.
Tue Aug 24 21:57:15 2021 - [info] Master MHA Node version is 0.58.
Tue Aug 24 21:57:15 2021 - [info] Checking recovery script configurations on 192.168.64.11(192.168.64.11:3306)..
Tue Aug 24 21:57:15 2021 - [info]   Executing command: save_binary_logs --command=test --start_pos=4 --binlog_dir=/data/software/mysql/data --output_file=/var/tmp/save_binary_logs_test --manager_version=0.58 --start_file=mysql-bin.000002 
Tue Aug 24 21:57:15 2021 - [info]   Connecting to [email protected](192.168.64.11:22).. 
  Creating /var/tmp if not exists..    ok.
  Checking output directory is accessible or not..
   ok.
  Binlog found at /data/software/mysql/data, up to mysql-bin.000002
Tue Aug 24 21:57:15 2021 - [info] Binlog setting check done.
Tue Aug 24 21:57:15 2021 - [info] Checking SSH publickey authentication and checking recovery script configurations on all alive slave servers..
Tue Aug 24 21:57:15 2021 - [info]   Executing command : apply_diff_relay_logs --command=test --slave_user='mhauser' --slave_host=192.168.64.12 --slave_ip=192.168.64.12 --slave_port=3306 --workdir=/var/tmp --target_version=5.7.27-log --manager_version=0.58 --relay_log_info=/data/software/mysql/data/relay-log.info  --relay_dir=/data/software/mysql/data/  --slave_pass=xxx
Tue Aug 24 21:57:15 2021 - [info]   Connecting to [email protected](192.168.64.12:22).. 
  Checking slave recovery environment settings..
    Opening /data/software/mysql/data/relay-log.info ... ok.
    Relay log found at /data/software/mysql/data, up to slave1-relay-bin.000002
    Temporary relay log file is /data/software/mysql/data/slave1-relay-bin.000002
    Checking if super_read_only is defined and turned on.. not present or turned off, ignoring.
    Testing mysql connection and privileges..
mysql: [Warning] Using a password on the command line interface can be insecure.
 done.
    Testing mysqlbinlog output.. done.
    Cleaning up test file(s).. done.
Tue Aug 24 21:57:16 2021 - [info]   Executing command : apply_diff_relay_logs --command=test --slave_user='mhauser' --slave_host=192.168.64.13 --slave_ip=192.168.64.13 --slave_port=3306 --workdir=/var/tmp --target_version=5.7.27-log --manager_version=0.58 --relay_log_info=/data/software/mysql/data/relay-log.info  --relay_dir=/data/software/mysql/data/  --slave_pass=xxx
Tue Aug 24 21:57:16 2021 - [info]   Connecting to [email protected](192.168.64.13:22).. 
  Checking slave recovery environment settings..
    Opening /data/software/mysql/data/relay-log.info ... ok.
    Relay log found at /data/software/mysql/data, up to slave2-relay-bin.000002
    Temporary relay log file is /data/software/mysql/data/slave2-relay-bin.000002
    Checking if super_read_only is defined and turned on.. not present or turned off, ignoring.
    Testing mysql connection and privileges..
mysql: [Warning] Using a password on the command line interface can be insecure.
 done.
    Testing mysqlbinlog output.. done.
    Cleaning up test file(s).. done.
Tue Aug 24 21:57:16 2021 - [info] Slaves settings check done.
Tue Aug 24 21:57:16 2021 - [info] 
192.168.64.11(192.168.64.11:3306) (current master)
 +--192.168.64.12(192.168.64.12:3306)
 +--192.168.64.13(192.168.64.13:3306)

Tue Aug 24 21:57:16 2021 - [info] Checking replication health on 192.168.64.12..
Tue Aug 24 21:57:16 2021 - [info]  ok.
Tue Aug 24 21:57:16 2021 - [info] Checking replication health on 192.168.64.13..
Tue Aug 24 21:57:16 2021 - [info]  ok.
Tue Aug 24 21:57:16 2021 - [info] Checking master_ip_failover_script status:
Tue Aug 24 21:57:16 2021 - [info]   /usr/local/bin/master_ip_failover --command=status --ssh_user=root --orig_master_host=192.168.64.11 --orig_master_ip=192.168.64.11 --orig_master_port=3306 
Checking the Status of the script.. OK 
Svip: Unknown host
ifconfig: `--help' gives usage information.
Tue Aug 24 21:57:16 2021 - [info]  OK.
Tue Aug 24 21:57:16 2021 - [warning] shutdown_script is not defined.
Tue Aug 24 21:57:16 2021 - [info] Got exit code 0 (Not master dead).

MySQL Replication Health is OK.
           
17、啟動MHA,背景啟動
[[email protected]_192.168.64.10 22:27:54/etc/mastermha]# nohup masterha_manager --conf=/etc/mastermha/app1.cnf &> /dev/null &
[1] 15392


# 檢查MHA狀态
[[email protected]_192.168.64.10 22:28:03/etc/mastermha]# masterha_check_status --conf=/etc/mastermha/app1.cnf 
app1 (pid:15392) is running(0:PING_OK), master:192.168.64.11
           
18、測試崩潰master,直接關閉master伺服器
[[email protected]_192.168.64.11 22:46:20~]# init 6
Connection closing...Socket close.

Connection closed by foreign host.

Disconnected from remote host(master) at 22:46:23.

Type `help' to learn how to use Xshell prompt.
[H:\~]$ 
           
檢視MHA日志
tail -f /data/mastermha/app1/manager.log

略略略。。。。


----- Failover Report -----

app1: MySQL Master failover 192.168.64.11(192.168.64.11:3306) to 192.168.64.12(192.168.64.12:3306) succeeded

Master 192.168.64.11(192.168.64.11:3306) is down!

Check MHA Manager logs at mha:/data/mastermha/app1/manager.log for details.

Started automated(non-interactive) failover.
Invalidated master IP address on 192.168.64.11(192.168.64.11:3306)
The latest slave 192.168.64.12(192.168.64.12:3306) has all relay logs for recovery.
Selected 192.168.64.12(192.168.64.12:3306) as a new master.
192.168.64.12(192.168.64.12:3306): OK: Applying all logs succeeded.
192.168.64.12(192.168.64.12:3306): OK: Activated master IP address.
192.168.64.13(192.168.64.13:3306): This host has the latest relay log events.
Generating relay diff files from the latest slave succeeded.
192.168.64.13(192.168.64.13:3306): OK: Applying all logs succeeded. Slave started, replicating from 192.168.64.12(192.168.64.12:3306)
192.168.64.12(192.168.64.12:3306): Resetting slave info succeeded.
Master failover to 192.168.64.12(192.168.64.12:3306) completed successfully.
Tue Aug 24 22:46:51 2021 - [info] Sending mail..
           
19、MHA是一次性的,如果需要再次運作MHA,需要删除日志檔案
[[email protected]_192.168.64.10 22:52:58~]# rm -f /data/mastermha/app1/app1.failover.complete 
           

三、Ansible介紹

官網: https://www.ansible.com/

官方文檔: https://docs.ansible.com/

  • Ansible的特性

1、子產品化:調用特定的子產品完成特定任務,支援自定義子產品,可使用任何程式設計語言寫子產品

2、Paramiko (python對ssh的實作),PyYAML,Jinja2(模闆語言)三個關鍵子產品

3、基于Python語言實作

4、部署簡單,基于python和SSH(預設已安裝),agentless,無需代理不依賴PKI(無需ssl)

5、安全,基于OpenSSH

6、幂等性:一個任務執行1遍和執行n遍效果一樣,不因重複執行帶來意外情況,此特性非絕對

7、支援playbook編排任務,YAML格式,編排任務,支援豐富的資料結構

8、較強大的多層解決方案role

  • Ansible的組成
2--MyCAT中間件和ansible基礎三、Ansible介紹

 1、組合INVENTORY、API、MODULES、PLUGINS的綠框,為ansible指令工具,其為核心執行工具

2、INVENTORY:Ansible管理主機的清單/etc/anaible/hosts

3、MODULES:Ansible執行指令的功能子產品,多數為内置核心子產品,也可自定義

4、PLUGINS:子產品功能的補充,如連接配接類型插件、循環插件、變量插件、過濾插件等,該功能不常用

5、API:供第三方程式調用的應用程式程式設計接口

  • Ansible的指令執行來源

1、USER普通使用者,即SYSTEM ADMINISTRATOR

2、PLAYBOOKS:任務劇本(任務集),編排定義Ansible任務集的配置檔案,由Ansible順序依次執行,通常是JSON格式的YML檔案

3、CMDB(配置管理資料庫)API調用

4、PUBLIC/PRIVATE CLOUD API調用

5、USER-> Ansible Playbook ->Ansibile

  • Ansible的注意事項

1、執行ansible的主機一般稱為管理端,主要端,中控,master或堡壘機

2、主要端Python版本需要2.6或以上

3、被控端Python版本小于2.4,需要安裝python-simplejson

4、被控端如開啟SELinux需要安裝libselinux-python

5、windows不能做為主要端

  • Ansible的安裝

1、官方文檔:https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.ht

2、下載下傳位址:https://releases.ansible.com/ansible/

  • Ansible的相關配置檔案

1、/etclansiblelansible.cfg主配置檔案,配置ansible工作特性

2、/etclansible/hosts主機清單

3、/etclansible/roles/存放角色的目錄

  • ansible的主配置檔案:/etc/ansible/ansible.cfg
[defaults]
# inventory = /etc/ansible/hosts       # 主機清單配置檔案
# library = /usr/share/my_modules/     # 庫檔案存放目錄
# remote_tmp = $HOME/.ansible/tmp      # 臨時py指令檔案存放在遠端主機目錄
# local_tmp = $HOME/.ansible/tmp       # 本機的臨時指令執行目錄
# forks =5                             # 預設并發數
# sudo_user = root                     # 預設sudo 使用者
# ask_sudo_pass = True                 # 每次執行ansible指令是否詢問ssh密碼
# ask_pass = True
# remote_port = 22
# host_key_checking = False            # 檢查對應伺服器的host_key,建議取消注釋
# log_path=/var/log/ansible.log        # 日志檔案,建議啟用
# module_name = command                # 預設子產品,可以修改為shell子產品
           
  • inventory主機清單

1、ansible的主要功用在于批量主機操作,為了便捷地使用其中的部分主機,可以在inventory file中将其分組命名

2、預設的inventory file為/etc/ansible/hosts

3、inventory file可以有多個,且也可以通過Dynamic Inventory來動态生成

4、官方文檔:https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html

  • 主機清單檔案格式

1、inventory檔案遵循INl檔案風格,中括号中的字元為組名。可以将同一個主機同時歸并到多個不同的組中

2、此外,當如若目标主機使用了非預設的SSH端口,還可以在主機名稱之後使用冒号加端口号來标明

3、如果主機名稱遵循相似的命名模式,還可以使用清單的方式辨別各主機

4、範例:

ntp.magedu.com
[webservers]
www1.magedu.com:2222
www2.magedu.com

[dbservers]
db1.magedu.com
db2.magedu.com
db3.magedu.com

[websrvs]
ww[1:100].example.com

[dbsrvs]
db-[a:f].example.com

[appsrvs]
10.0.0.[1:100]

[test]
10.0.0.8   ansible_connection=local=l    # 指定本地連接配接,無需ssh配置

# ansible_connection=ssh 需要strictHostKeychecking no
10.0.0.7 ansible_connection=ssh ansible_port=2222 ansible_user=wangansible_password=magedu
10.0.0.6 ansible_connection=ssh ansible_user=root ansible_password=123456
           
  • Ansible的相關工具

1、/usr/bin/ansible                          主程式,臨時指令執行工具

2、/usr/bin/ansible-doc                   檢視配置文檔,子產品功能檢視工具,相當于man

3、/usr/bin/ansible-playbook          定制自動化任務,編排劇本工具,相當于腳本,主要用于長期規劃好的,大型項目的場景,需要有前期的規劃過程

4、/usr/bin/ansible-pull                   遠端執行指令的工具

5、usr/bin/ansible-vault                  檔案加密工具

6、/usr/bin/ansible-console            基于Console界面與使用者互動的執行工具

7、/usr/bin/ansible-galaxy              下載下傳/上傳優秀代碼或Roles子產品的官網平台

四、Ansible常用子產品

官網:https://docs.ansible.com/ansible/2.9/modules/modules_by_category.html

https://docs.ansible.com/ansible/latest/modules/modules_by_category.html

  • ping子產品

功能:測試主機的連通性

範例:

[[email protected] 11:39:51~]# ansible all -m ping
192.168.64.10 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
192.168.64.11 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
192.168.64.12 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
[[email protected] 11:39:56~]# 
           
  • Command子產品

功能:在遠端主機執行指令,此為預設子產品,可忽略-m選項

注意:此指令不支援$VARNAME< > |;&等,用shell子產品可實作特殊符号實作

範例:

[[email protected] 11:47:23~]# ansible all -m command -a 'chdir=/root ls -l'
192.168.64.10 | CHANGED | rc=0 >>
總用量 4
-rw-------. 1 root root 1407 3月  13 08:34 anaconda-ks.cfg
192.168.64.11 | CHANGED | rc=0 >>
總用量 4
-rw-------. 1 root root 1407 3月  13 08:34 anaconda-ks.cfg
192.168.64.12 | CHANGED | rc=0 >>
總用量 4
-rw-------. 1 root root 1407 3月  13 08:34 anaconda-ks.cfg
[[email protected] 11:47:50~]# ansible all -a 'chdir=/root ls -l'
192.168.64.10 | CHANGED | rc=0 >>
總用量 4
-rw-------. 1 root root 1407 3月  13 08:34 anaconda-ks.cfg
192.168.64.11 | CHANGED | rc=0 >>
總用量 4
-rw-------. 1 root root 1407 3月  13 08:34 anaconda-ks.cfg
192.168.64.12 | CHANGED | rc=0 >>
總用量 4
-rw-------. 1 root root 1407 3月  13 08:34 anaconda-ks.cfg
[[email protected] 11:47:54~]# 
           
  •  shell子產品

功能:和command相似,用shell執行指令,支援各種符号,比如:*,$,>等,它不是預設子產品,需要加-m

範例:

[[email protected] 12:16:19~]# ansible all -m shell -a 'echo $UID'
192.168.64.10 | CHANGED | rc=0 >>
0
192.168.64.11 | CHANGED | rc=0 >>
0
192.168.64.12 | CHANGED | rc=0 >>
0
[[email protected] 12:16:54~]# 
           
  • script子產品

功能:在遠端主機上運作ansible伺服器上的腳本(無需執行權限)

範例:

[[email protected] 12:16:54~]# ansible all -m shell -a 'echo hostname -I > /root/test.sh'
192.168.64.10 | CHANGED | rc=0 >>

192.168.64.11 | CHANGED | rc=0 >>

192.168.64.12 | CHANGED | rc=0 >>

[[email protected] 12:22:43~]# ansible all -m script -a '/root/test.sh'
192.168.64.10 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "",
    "stderr_lines": [],
    "stdout": "192.168.64.10 \n",
    "stdout_lines": [
        "192.168.64.10 "
    ]
}
192.168.64.11 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 192.168.64.11 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 192.168.64.11 closed."
    ],
    "stdout": "192.168.64.11 \r\n",
    "stdout_lines": [
        "192.168.64.11 "
    ]
}
192.168.64.12 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 192.168.64.12 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 192.168.64.12 closed."
    ],
    "stdout": "192.168.64.12 \r\n",
    "stdout_lines": [
        "192.168.64.12 "
    ]
}
[[email protected] 12:23:13~]# 
           
  • copy子產品

功能:從ansible伺服器主要端複制檔案到遠端主機

注意:如果目标檔案已存在,則預設被覆寫;複制目錄目錄時要注意 '/' ,跟rsync一樣;如 /data 表示 /data 整個目錄包括 data 本身也複制過去;如 /data/  隻複制 /data 目錄下的檔案和子目錄過去

範例:

[[email protected] 12:45:07~]# mkdir /data
[[email protected] 12:45:11~]# touch /data/test.txt
[[email protected] 12:45:18~]# ansible all -m copy -a 'src=/data dest=/test'
192.168.64.10 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
    "dest": "/test/data/test.txt",
    "gid": 0,
    "group": "root",
    "md5sum": "d41d8cd98f00b204e9800998ecf8427e",
    "mode": "0644",
    "owner": "root",
    "size": 0,
    "src": "/root/.ansible/tmp/ansible-tmp-1630125944.9041228-5084-251443679463658/source",
    "state": "file",
    "uid": 0
}

略略略。。。

[[email protected] 12:45:46~]# ansible all -m shell -a 'ls -l /test/'
192.168.64.11 | CHANGED | rc=0 >>
總用量 0
drwxr-xr-x 2 root root 22 8月  28 12:45 data
192.168.64.12 | CHANGED | rc=0 >>
總用量 0
drwxr-xr-x 2 root root 22 8月  28 12:45 data
192.168.64.10 | CHANGED | rc=0 >>
總用量 0
drwxr-xr-x 2 root root 22 8月  28 12:45 data
[[email protected] 12:45:54~]# ansible all -m copy -a 'src=/data/ dest=/test'
192.168.64.10 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709",
    "dest": "/test/test.txt",
    "gid": 0,
    "group": "root",
    "md5sum": "d41d8cd98f00b204e9800998ecf8427e",
    "mode": "0644",
    "owner": "root",
    "size": 0,
    "src": "/root/.ansible/tmp/ansible-tmp-1630125962.354739-5224-180881665123159/source",
    "state": "file",
    "uid": 0
}

略略略。。。

[[email protected] 12:46:03~]# ansible all -m shell -a 'ls -l /test/'
192.168.64.10 | CHANGED | rc=0 >>
總用量 0
drwxr-xr-x 2 root root 22 8月  28 12:45 data
-rw-r--r-- 1 root root  0 8月  28 12:46 test.txt
192.168.64.11 | CHANGED | rc=0 >>
總用量 0
drwxr-xr-x 2 root root 22 8月  28 12:45 data
-rw-r--r-- 1 root root  0 8月  28 12:46 test.txt
192.168.64.12 | CHANGED | rc=0 >>
總用量 0
drwxr-xr-x 2 root root 22 8月  28 12:45 data
-rw-r--r-- 1 root root  0 8月  28 12:46 test.txt
[[email protected] 12:46:15~]# 
           
  • fetch子產品

功能:從遠端主機提取檔案至ansible的主要端,copy相反,目前不支援目錄

範例:

[[email protected] 12:50:19~]# ansible all -m fetch -a 'src=/etc/os-release dest=/data'
192.168.64.10 | CHANGED => {
    "changed": true,
    "checksum": "6e35f19e5774acd00f10342edef82a8247674028",
    "dest": "/data/192.168.64.10/etc/os-release",
    "md5sum": "0868a2ea7fc0d17dec85d63f452563d4",
    "remote_checksum": "6e35f19e5774acd00f10342edef82a8247674028",
    "remote_md5sum": null
}
192.168.64.12 | CHANGED => {
    "changed": true,
    "checksum": "6e35f19e5774acd00f10342edef82a8247674028",
    "dest": "/data/192.168.64.12/etc/os-release",
    "md5sum": "0868a2ea7fc0d17dec85d63f452563d4",
    "remote_checksum": "6e35f19e5774acd00f10342edef82a8247674028",
    "remote_md5sum": null
}
192.168.64.11 | CHANGED => {
    "changed": true,
    "checksum": "6e35f19e5774acd00f10342edef82a8247674028",
    "dest": "/data/192.168.64.11/etc/os-release",
    "md5sum": "0868a2ea7fc0d17dec85d63f452563d4",
    "remote_checksum": "6e35f19e5774acd00f10342edef82a8247674028",
    "remote_md5sum": null
}
[[email protected] 12:51:01~]# tree /data/
/data/
├── 192.168.64.10
│   └── etc
│       └── os-release
├── 192.168.64.11
│   └── etc
│       └── os-release
├── 192.168.64.12
│   └── etc
│       └── os-release
└── test.txt

6 directories, 4 files
[[email protected] 12:51:11~]# 
           
  • file子產品

功能:設定檔案屬性,建立軟連結等

範例:

[[email protected] 14:57:31~]# ansible all -m shell -a 'ls -l /test'
192.168.64.10 | CHANGED | rc=0 >>
總用量 0
drwxr-xr-x 2 root root 22 8月  28 12:45 data
-rw-r--r-- 1 root root  0 8月  28 12:46 test.txt
192.168.64.11 | CHANGED | rc=0 >>
總用量 0
drwxr-xr-x 2 root root 22 8月  28 12:45 data
-rw-r--r-- 1 root root  0 8月  28 12:46 test.txt
192.168.64.12 | CHANGED | rc=0 >>
總用量 0
drwxr-xr-x 2 root root 22 8月  28 12:45 data
-rw-r--r-- 1 root root  0 8月  28 12:46 test.txt
[[email protected] 15:08:51~]# ansible all -m file -a  'path=/test/test.txt owner=nobody group=nobody'
192.168.64.10 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "gid": 65534,
    "group": "nobody",
    "mode": "0644",
    "owner": "nobody",
    "path": "/test/test.txt",
    "size": 0,
    "state": "file",
    "uid": 65534
}
192.168.64.12 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "gid": 65534,
    "group": "nobody",
    "mode": "0644",
    "owner": "nobody",
    "path": "/test/test.txt",
    "size": 0,
    "state": "file",
    "uid": 65534
}
192.168.64.11 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "gid": 65534,
    "group": "nobody",
    "mode": "0644",
    "owner": "nobody",
    "path": "/test/test.txt",
    "size": 0,
    "state": "file",
    "uid": 65534
}
[[email protected] 15:12:03~]# ansible all -m shell -a 'ls -l /test'
192.168.64.10 | CHANGED | rc=0 >>
總用量 0
drwxr-xr-x 2 root   root   22 8月  28 12:45 data
-rw-r--r-- 1 nobody nobody  0 8月  28 12:46 test.txt
192.168.64.12 | CHANGED | rc=0 >>
總用量 0
drwxr-xr-x 2 root   root   22 8月  28 12:45 data
-rw-r--r-- 1 nobody nobody  0 8月  28 12:46 test.txt
192.168.64.11 | CHANGED | rc=0 >>
總用量 0
drwxr-xr-x 2 root   root   22 8月  28 12:45 data
-rw-r--r-- 1 nobody nobody  0 8月  28 12:46 test.txt
[[email protected] 15:12:10~]# 
           
  • unarchive子產品

功能:解包解壓縮

實作有兩種用法:

1、将ansible主機上的壓縮包傳到遠端主機後解壓縮至特定目錄,設定copy=yes

2、将遠端主機上的某個壓縮包解壓縮到指定路徑下,設定copy=no

常見參數:

copy:預設為yes,當copy=yes,拷貝的檔案是從ansible主機複制到遠端主機上,如果設定為copy=no,會在遠端主機上尋找src源檔案

remote_src:和copy功能一樣且互斥,yes表示在遠端主機,不在ansible主機,no表示檔案在ansib1e主機上

src:源路徑,可以是ansible主機上的路徑,也可以是遠端主機(被管理端或者第三方主機)上的路徑,如果是遠端主機上的路徑,則需要設定copy=no

dest:遠端主機上的目标路徑

mode:設定解壓縮後的檔案權限

範例:

[[email protected] 21:45:19~]# tar -zcf data.tar.gz /data/
tar: 從成員名中删除開頭的“/”
[[email protected] 21:45:40~]# ansible all -m shell -a 'ls -l /test/data'
192.168.64.10 | CHANGED | rc=0 >>
總用量 0
-rw-r--r-- 1 root root 0 8月  28 12:45 test.txt
192.168.64.11 | CHANGED | rc=0 >>
總用量 0
-rw-r--r-- 1 root root 0 8月  28 12:45 test.txt
192.168.64.12 | CHANGED | rc=0 >>
總用量 0
-rw-r--r-- 1 root root 0 8月  28 12:45 test.txt
[[email protected] 21:45:47~]# ansible all -m unarchive -a 'src=/root/data.tar.gz dest=/test/data/ owner=nobody'
192.168.64.10 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "dest": "/test/data/",
    "extract_results": {
        "cmd": [
            "/usr/bin/gtar",
            "--extract",
            "-C",
            "/test/data/",
            "-z",
            "--owner=nobody",
            "-f",
            "/root/.ansible/tmp/ansible-tmp-1630158354.7565894-7394-37836325727783/source"
        ],
        "err": "",
        "out": "",
        "rc": 0
    },
    "gid": 0,
    "group": "root",
    "handler": "TgzArchive",
    "mode": "0755",
    "owner": "root",
    "size": 34,
    "src": "/root/.ansible/tmp/ansible-tmp-1630158354.7565894-7394-37836325727783/source",
    "state": "directory",
    "uid": 0
}

略略略。。。

[[email protected] 21:45:56~]# ansible all -m shell -a 'ls -l /test/data'
192.168.64.10 | CHANGED | rc=0 >>
總用量 0
drwxr-xr-x 5 nobody root 85 8月  28 12:51 data
-rw-r--r-- 1 root   root  0 8月  28 12:45 test.txt
192.168.64.11 | CHANGED | rc=0 >>
總用量 0
drwxr-xr-x 5 nobody root 85 8月  28 12:51 data
-rw-r--r-- 1 root   root  0 8月  28 12:45 test.txt
192.168.64.12 | CHANGED | rc=0 >>
總用量 0
drwxr-xr-x 5 nobody root 85 8月  28 12:51 data
-rw-r--r-- 1 root   root  0 8月  28 12:45 test.txt
[[email protected] 21:46:00~]# 
           
  • archive子產品

功能:打包壓縮儲存在被管理節點

範例:

[[email protected] 21:55:12~]# ansible all -m file -a 'path=/data_log state=directory'
192.168.64.10 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "gid": 0,
    "group": "root",
    "mode": "0755",
    "owner": "root",
    "path": "/data_log",
    "size": 6,
    "state": "directory",
    "uid": 0
}
192.168.64.12 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "gid": 0,
    "group": "root",
    "mode": "0755",
    "owner": "root",
    "path": "/data_log",
    "size": 6,
    "state": "directory",
    "uid": 0
}
192.168.64.11 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "gid": 0,
    "group": "root",
    "mode": "0755",
    "owner": "root",
    "path": "/data_log",
    "size": 6,
    "state": "directory",
    "uid": 0
}

[[email protected] 21:56:18~]# ansible all -m shell -a 'ls -l /data_log'
192.168.64.10 | CHANGED | rc=0 >>
總用量 0
192.168.64.12 | CHANGED | rc=0 >>
總用量 0
192.168.64.11 | CHANGED | rc=0 >>
總用量 0
[[email protected] 21:56:40~]# ansible all -m archive -a 'path=/test/data dest=/data_log/test.tar.gz format=gz owner=bin mode=0644'
192.168.64.10 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "archived": [
        "/test/data/test.txt",
        "/test/data/data/test.txt",
        "/test/data/data/192.168.64.10/etc/os-release",
        "/test/data/data/192.168.64.12/etc/os-release",
        "/test/data/data/192.168.64.11/etc/os-release"
    ],
    "arcroot": "/test/",
    "changed": true,
    "dest": "/data_log/test.tar.gz",
    "expanded_exclude_paths": [],
    "expanded_paths": [
        "/test/data"
    ],
    "gid": 0,
    "group": "root",
    "missing": [],
    "mode": "0644",
    "owner": "bin",
    "size": 519,
    "state": "file",
    "uid": 1
}

略略略。。。

[[email protected] 21:56:46~]# ansible all -m shell -a 'ls -l /data_log'
192.168.64.10 | CHANGED | rc=0 >>
總用量 4
-rw-r--r-- 1 bin root 519 8月  28 21:56 test.tar.gz
192.168.64.12 | CHANGED | rc=0 >>
總用量 4
-rw-r--r-- 1 bin root 519 8月  28 21:56 test.tar.gz
192.168.64.11 | CHANGED | rc=0 >>
總用量 4
-rw-r--r-- 1 bin root 519 8月  28 21:56 test.tar.gz
[[email protected] 21:56:51~]# 
           
  • hostname子產品

功能:管理主機名

範例:

[[email protected] 22:08:22~]# ansible 192.168.64.11 -m shell -a 'hostname'
192.168.64.11 | CHANGED | rc=0 >>
client1
[[email protected] 22:08:46~]# ansible 192.168.64.11 -m hostname -a 'name=slave-64.11'
192.168.64.11 | CHANGED => {
    "ansible_facts": {
        "ansible_domain": "11",
        "ansible_fqdn": "slave-64.11",
        "ansible_hostname": "slave-64",
        "ansible_nodename": "slave-64.11",
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "name": "slave-64.11"
}
[[email protected] 22:08:54~]# ansible 192.168.64.11 -m shell -a 'hostname'
192.168.64.11 | CHANGED | rc=0 >>
slave-64.11
           
  • cron子產品

功能:計劃任務

支援時間:minute(分),hour(時),day(日),month(月),weekday(周)

  • yum和apt子產品

功能:yum管理軟體包,隻THEL、centos、fedora,不支援ubuntu等其他系統版本

apt子產品管理debian相關版本的軟體包

範例:

安裝:
[[email protected] 22:09:12~]# ansible all -m yum -a 'name=httpd state=present'

删除:
[[email protected] 22:23:06~]# ansible all -m yum -a 'name=httpd state=absent'
           
  • service子產品

功能:管理軟體服務

範例:

安裝httpd服務:
[[email protected] 22:26:05~]# ansible all -m yum -a 'name=httpd state=present'

啟動httpd服務并設定開機自啟
[[email protected] 22:26:12~]# ansible all -m service -a 'name=httpd state=started enabled=yes'
           
  • group子產品

功能:管理組

範例:

添加nginx組
[[email protected] 23:02:20~]# ansible all -m group -a 'name=nginx gid=1200 system=yes'

删除組
[[email protected] 23:02:31~]# ansible all -m group -a 'name=nginx state=absent'
           
  • user子產品

功能:管理使用者

範例:

先添加nginx組
[[email protected] 23:03:05~]# ansible all -m group -a 'name=nginx gid=1200 system=yes'

添加nginx使用者
[[email protected] 23:03:08~]# ansible all -m user -a 'name=nginx comment=nginx uid=1200 group=nginx groups="root,daemon" shell=/sbin/nologin system=yes create_home=no home=/data/nginx non_unique=yes'

檢視建立的nginx使用者
[[email protected] 23:05:10~]# ansible all -a 'getent passwd nginx'

删除使用者,順便nginx家目錄也删除
[[email protected] 23:05:20~]# ansible all -m user -a 'name=nginx state=absent remove=yes'
           
  •  lineinfile子產品

1、ansible在使用sed進行替換時,經常會遇到需要轉義的問題,而且ansible在遇到特殊符号進行替換時,存在問題,無法正常進行替換。其實在ansible自身提供了兩個子產品:lineinfile子產品和replace子產品,可以友善的進行替換

2、一般在ansible當中去修改某個檔案的單行進行替換的時候需要使用lineinfile子產品

3、regexp參數:使用正規表達式比對對應的行,當替換文本時,如果有多行文本都能被比對,則隻有最後面被比對到的那行文本才會被替換,當删除文本時,如果有多行文本都能被比對,這麼這些行都會被删除。

4、如果想進行多行比對進行替換需要使用replace子產品

功能:相當于sed,可以修改檔案内容

範例:

[[email protected] 23:21:37~]# ansible all -m shell -a 'grep '^Listen' /etc/httpd/conf/httpd.conf'
192.168.64.10 | CHANGED | rc=0 >>
Listen 80
192.168.64.11 | CHANGED | rc=0 >>
Listen 80
192.168.64.12 | CHANGED | rc=0 >>
Listen 80

[[email protected] 23:22:34~]# ansible all -m lineinfile -a "path=/etc/httpd/conf/httpd.conf regexp='^Listen' line='Listen 8080'"
192.168.64.10 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "backup": "",
    "changed": true,
    "msg": "line replaced"
}
192.168.64.12 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "backup": "",
    "changed": true,
    "msg": "line replaced"
}
192.168.64.11 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "backup": "",
    "changed": true,
    "msg": "line replaced"
}

[[email protected] 23:22:44~]# ansible all -m shell -a 'grep '^Listen' /etc/httpd/conf/httpd.conf'
192.168.64.10 | CHANGED | rc=0 >>
Listen 8080
192.168.64.11 | CHANGED | rc=0 >>
Listen 8080
192.168.64.12 | CHANGED | rc=0 >>
Listen 8080
 
           
  • replace子產品

該子產品有點類似于sed指令,主要也是基于正則進行比對和替換,建議使用

範例:

[[email protected] 23:34:57~]# cat /etc/fstab 

#
# /etc/fstab
# Created by anaconda on Sat Mar 13 00:29:06 2021
#
# Accessible filesystems, by reference, are maintained under '/dev/disk/'.
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info.
#
# After editing this file, run 'systemctl daemon-reload' to update systemd
# units generated from this file.
#
/dev/mapper/cl-root     /                       xfs     defaults        0 0
UUID=c72572c5-7e9e-470b-b95d-535233f69ab8 /boot                   xfs     defaults        0 0
/dev/mapper/cl-home     /home                   xfs     defaults        0 0
/dev/mapper/cl-swap     none                    swap    defaults        0 0
[[email protected] 23:34:58~]# ansible 192.168.64.10 -m replace -a "path=/etc/fstab regexp='^(#.*)' replace='#\1'"
192.168.64.10 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "msg": "10 replacements made"
}
[[email protected] 23:35:28~]# cat /etc/fstab 

##
## /etc/fstab
## Created by anaconda on Sat Mar 13 00:29:06 2021
##
## Accessible filesystems, by reference, are maintained under '/dev/disk/'.
## See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info.
##
## After editing this file, run 'systemctl daemon-reload' to update systemd
## units generated from this file.
##
/dev/mapper/cl-root     /                       xfs     defaults        0 0
UUID=c72572c5-7e9e-470b-b95d-535233f69ab8 /boot                   xfs     defaults        0 0
/dev/mapper/cl-home     /home                   xfs     defaults        0 0
/dev/mapper/cl-swap     none                    swap    defaults        0 0
[[email protected] 23:35:33~]# ansible 192.168.64.10 -m replace -a "path=/etc/fstab regexp='^#(#?.*)' replace='\1'"
192.168.64.10 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "msg": "10 replacements made"
}
[[email protected] 23:35:40~]# cat /etc/fstab 

#
# /etc/fstab
# Created by anaconda on Sat Mar 13 00:29:06 2021
#
# Accessible filesystems, by reference, are maintained under '/dev/disk/'.
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info.
#
# After editing this file, run 'systemctl daemon-reload' to update systemd
# units generated from this file.
#
/dev/mapper/cl-root     /                       xfs     defaults        0 0
UUID=c72572c5-7e9e-470b-b95d-535233f69ab8 /boot                   xfs     defaults        0 0
/dev/mapper/cl-home     /home                   xfs     defaults        0 0
/dev/mapper/cl-swap     none                    swap    defaults        0 0
           
  • setup子產品

功能:setup子產品來收集主機的系統資訊,這些facts 資訊可以直接以變量的形式使用,但是如果主機較多,會影響執行速度,可以使用gather_facts:no來禁止Ansible 收集facts資訊

1、ansible_all_ipv4_addresses:僅顯示ipv4的資訊

2、ansible_devices:僅顯示磁盤裝置資訊

3、ansible_distribution:顯示是什麼系統,例:centos,suse等

4、ansible_distribution_major_version:顯示是系統主版本

5、ansible_distribution_version:僅顯示系統版本

6、ansible_machine:顯示系統類型,例:32位,還是64位

7、ansible_eth0:僅顯示eth0的資訊

8、ansible_hostname:僅顯示主機名

9、ansible_kernel:僅顯示核心版本

10、ansible_lvm:顯示lvm相關資訊

11、ansible_memtotal_mb:顯示系統總記憶體

12、ansible_memfree_mb:顯示可用系統記憶體

13、ansible_memory_mb:詳細顯示記憶體情況

14、ansible_swaptotal_mb:顯示總的swap記憶體

15、ansible_swapfree_mb:顯示swap記憶體的可用記憶體

16、ansible_mounts:顯示系統磁盤挂載情況

17、ansible_processor:顯示cpu個數(具體顯示每個cpu的型号)

18、ansible_processor_vcpus:顯示cpu個數(隻顯示總的個數)

[[email protected] 23:40:36~]# ansible all -m setup -a 'filter=ansible_processor_vcpus'
192.168.64.10 | SUCCESS => {
    "ansible_facts": {
        "ansible_processor_vcpus": 4,
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}
192.168.64.12 | SUCCESS => {
    "ansible_facts": {
        "ansible_processor_vcpus": 4,
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}
192.168.64.11 | SUCCESS => {
    "ansible_facts": {
        "ansible_processor_vcpus": 4,
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false
}
[[email protected] 23:45:49~]# 
           

五、YAML語言

YAML官方網站:http://www.yaml.org

六、ansible-playbook批量安裝httpd,并修改index.html頁面

[[email protected] 10:36:30~]# cat install_httpd.yml 
- hosts: all
  remote_user: root
  gather_facts: no

  tasks:
    - name: install httpd
      yum: name=httpd
    - name: update index.html
      shell: echo welcome $HOSTNAME > /var/www/html/index.html
    - name: start
      service: name=httpd state=started enabled=yes
[[email protected] 10:36:36~]# ansible-playbook install_httpd.yml 

PLAY [all] ******************************************************************************************************************

TASK [install httpd] ********************************************************************************************************
changed: [192.168.64.11]
changed: [192.168.64.10]
changed: [192.168.64.12]

TASK [update index.html] ****************************************************************************************************
changed: [192.168.64.10]
changed: [192.168.64.11]
changed: [192.168.64.12]

TASK [start] ****************************************************************************************************************
changed: [192.168.64.10]
changed: [192.168.64.12]
changed: [192.168.64.11]

PLAY RECAP ******************************************************************************************************************
192.168.64.10              : ok=3    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.64.11              : ok=3    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.64.12              : ok=3    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

[[email protected] 10:36:55~]# curl http://192.168.64.10/index.html
welcome server
[[email protected] 10:37:44~]# curl http://192.168.64.11/index.html
welcome client1
[[email protected] 10:37:48~]# curl http://192.168.64.12/index.html
welcome client2
[[email protected] 10:37:52~]# 
           

7、redis編譯安裝

系統:

[[email protected]_192.168.64.132 21:23:39~]# cat /etc/os-release 
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"
           
Redis安裝包:redis-6.0.0.tar.gz

編譯安裝:

[[email protected]_192.168.64.132 21:23:51~]# mkdir /data/software -p
[[email protected]_192.168.64.132 21:23:56~]# rz -E
rz waiting to receive.
[[email protected]_192.168.64.132 21:24:01~]# ll
total 2160
-rw-------. 1 root root    1457 Nov  8  2020 anaconda-ks.cfg
-rw-r--r--  1 root root 2204177 Aug 29 21:15 redis-6.0.0.tar.gz
[[email protected]_192.168.64.132 21:24:04~]# tar zxf redis-6.0.0.tar.gz
[[email protected]_192.168.64.132 21:24:34~]# mv redis-6.0.0 /data/software/redis/
[[email protected]_192.168.64.132 21:24:34~]# cd /data/software/redis/

# 删除舊的yum源
[[email protected]_192.168.64.132 21:27:08/data/software/redis]# rm /etc/yum.repos.d/* -f

# 添加清華源
[[email protected]_192.168.64.132 21:31:19/data/software/redis]# cat /etc/yum.repos.d/CentOS-Base.repo 
# CentOS-Base.repo

[base]
name=CentOS-$releasever - Base
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
 
[updates]
name=CentOS-$releasever - Updates
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
 
[extras]
name=CentOS-$releasever - Extras
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
 
[centosplus]
name=CentOS-$releasever - Plus
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/centosplus/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

[[email protected]_192.168.64.132 21:31:27/data/software/redis]# yum -y install epel-release.noarch

[[email protected]_192.168.64.132 21:32:36/data/software/redis]# yum -y install centos-release-scl gcc gcc-c++

[[email protected]_192.168.64.132 21:34:16/data/software/redis]# yum -y install devtoolset-9-gcc devtoolset-9-gcc-c++ devtoolset-9-binutils

[[email protected]_192.168.64.132 21:34:55/data/software/redis]# scl enable devtoolset-9 bash

[[email protected]_192.168.64.132 21:35:20/data/software/redis]# echo "source /opt/rh/devtoolset-9/enable" >> /etc/profile

[[email protected]_192.168.64.132 21:35:38/data/software/redis]# make install PREFIX=/data/software/redis

[[email protected]_192.168.64.132 21:37:07/data/software/redis]# cat > /data/software/redis/redis.conf <<EOF
bind 127.0.0.1
requirepass OhpJvZPY4Y8rcBKZMe43m5w6WhjJwkFxgKS77YX3EoWS7gAhK
protected-mode yes
tcp-backlog 500
unixsocket /data/software/redis/tmp/redis.sock
timeout 0
daemonize no
supervised auto
pidfile /data/software/redis/run/redis.pid
loglevel notice
logfile "/data/software/redis/log/redis.log"
databases 16
always-show-logo yes
save 900 1
save 300 10
save 60 10000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
dir /data/software/redis/data
replica-serve-stale-data yes
replica-read-only yes
repl-diskless-sync no
repl-diskless-sync-delay 5
repl-disable-tcp-nodelay no
replica-priority 100
lazyfree-lazy-eviction no
lazyfree-lazy-expire no
lazyfree-lazy-server-del no
replica-lazy-flush no
appendonly no
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
aof-use-rdb-preamble yes
lua-time-limit 5000
slowlog-log-slower-than 10000
slowlog-max-len 128
latency-monitor-threshold 0
notify-keyspace-events ""
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-size -2
list-compress-depth 0
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
hll-sparse-max-bytes 3000
stream-node-max-bytes 4096
stream-node-max-entries 100
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit replica 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
hz 10
dynamic-hz yes
aof-rewrite-incremental-fsync yes
rdb-save-incremental-fsync yes
EOF

[[email protected]_192.168.64.132 21:37:52/data/software/redis]# cd /data/software/redis && mkdir data log tmp

[[email protected]_192.168.64.132 21:37:58/data/software/redis]# /data/software/redis/bin/redis-server /data/software/redis/redis.conf &
[1] 6149

[[email protected]_192.168.64.132 21:38:00/data/software/redis]# cat > /etc/profile.d/redis_home.sh <<EOF
> REDIS_HOME=/data/software/redis
> export PATH=\$PATH:\$REDIS_HOME/bin
> EOF

[[email protected]_192.168.64.132 21:38:06/data/software/redis]# source /etc/profile

[[email protected]_192.168.64.132 21:38:48/data/software/redis]# echo '/data/software/redis/bin/redis-server /data/software/redis/redis.conf &' >> /etc/rc.local 

[[email protected]_192.168.64.132 21:38:58/data/software/redis]# chmod +x /etc/rc.local /etc/rc.d/rc.local
           

繼續閱讀