0%

一、介绍

集群基本概念

  • Cluster 代表一个集群
  • Shards 代表索引分片,分布在不同节点上,构成分部署搜索。分片数量在创建索引时指定,不能修改。
  • Replicas 副本,提高系统的容错性,提高查询效率。ES 会自动对请求进行负载均衡。
  • Recovery数据重新分布,ES 在节点加入或退出时,会根据机器的负载对索引分片进行重新分配,挂掉的节点重新启动时也会进行数据恢复。

ES 高并发

ES是一个分布式全文检索框架,隐藏了复杂的处理机制,内部使用 分片机制、集群发现、分片负载均衡请求路由。

  • Shards 实现了分布式检索。
  • Replicas 实现了负载均衡与容错恢复。

附上官网地址

二、准备

集群架构

部署服务器方案

使用 HaProxy 负载

cluster.name: my-cluster

  1. ELK8:192.168.2.8 es-node1
  2. ELK9:192.168.2.9 es-node2
  3. ELK10:192.168.2.10 es-node3

三、ES 安装

解压安装

下载

下载地址 or ES start

下载 elasticsearch-7.14.0-linux-x86_64.tar.gzkibana-7.14.0-linux-x86_64.tar.gz

解压

1
2
3
4
tar -zxvf elasticsearch-7.14.0-linux-x86_64.tar.gz
mv elasticsearch-7.14.0 /opt/elasticsearch-7.14.0
tar -zxvf kibana-7.14.0-linux-x86_64.tar.gz
mv kibana-7.14.0-linux-x86_64 /opt/kibana-7.14.0

添加用户

1
2
3
4
5
6
7
8
9
10
11
# 添加账号
useradd es
# 修改密码
passwd es
# 把用户加入到 root 组
usermod -aG root es
# 加入到 sudo 中
sudo vim /etc/sudoers
# 添加一行: es ALL=(ALL) ALL
su es
sudo chown es ./

Centos 系统配置

max file

修改

1
sudo vim /etc/security/limits.conf

添加

1
2
3
4
* soft nofile 65536
* hard nofile 65536
* soft nproc 65536
* hard nproc 65536

执行

1
sudo source /etc/security/limits.conf

virtual memory

1
2
3
4
sudo vim /etc/sysctl.conf
# 添加 一行 vm.max_map_count=655360
# 重新加载参数
sudo sysctl -p

核心配置

ElasticSearch

1
vim /opt/elasticsearch-7.14.0/config/elasticsearch.yml

修改为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 集群名称,在集群中不能重复,默认为  elasticsearch
cluster.name: my-cluster
# 集群节点描述
node.name: es-node8
# data数据保存路径,默认为 elasticsearch/data
#path.data: /path/to/data
# 日志数据保存路径,默认为 elasticsearch/logs
#path.logs: /path/to/logs
# 绑定地址,所有人都可以访问
network.host: 0.0.0.0
# 绑定端口,用于外部通讯(9300端口:Tcp协议,ES集群之间的通讯)
http.port: 9200
# 集群的节点,单机就写上面的节点名称
cluster.initial_master_nodes: ["es-node8","es-node9","es-node10"]

Kibana

1
vim /opt/kibana-7.14.0/config/kibana.yml

修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 端口
server.port: 5601
# 本机IP
server.host: "192.168.2.2"
# 请求最大负载大小
#server.maxPayload: 1048576
# 服务名称
server.name: "kibana-host2"
# Elasticsearch instances.
elasticsearch.hosts: ["http://192.168.2.2:9200"]
# 如果你的Elasticsearch受基本身份验证的保护,这些设置将提供Kibana服务器在启动时用于维护Kibana索引的用户名和密码。Kibana的用户仍然需要通过Elasticsearch进行身份验证,Elasticsearch是通过Kibana服务器代理的。
elasticsearch.username: "maxzhao"
elasticsearch.password: "maxzhao"
xpack.security.sessionTimeout: 600000
# 随机数长度大于32 https://www.elastic.co/guide/en/kibana/current/reporting-settings-kb.html
xpack.reporting.encryptionKey: "11112222333344445555666677778888"
# https://www.elastic.co/guide/en/kibana/6.x/using-kibana-with-security.html
xpack.security.encryptionKey: "11112222333344445555666677778888"

启动

1
2
3
4
5
6
sudo chmod g+xwr /var
mkdir /var/data/
mkdir /var/log/
cd /opt
./elasticsearch-7.14.0/bin/elasticsearch
./kibana-7.14.0/bin/kibana

访问

  1. 访问ES http://127.0.0.1:9200/
  2. 访问kibana http://localhost:5601

后台启动

1
2
/opt/elasticsearch-7.14.0/bin/elasticsearch -d
/opt/kibana-7.14.0/bin/kibana -d

停止服务

1
2
3
ps -ef|grep elasticsearch
ps -ef|grep kibana
kill -9 xxx

启动方式

指定进程ID

进程ID写在文件中,方便关闭

1
2
/opt/elasticsearch-7.14.0/bin/elasticsearch -d -p pid
pkill -F pid

外部化配置

1
/opt/elasticsearch-7.14.0/bin/elasticsearch -d -Ecluster.name=my_cluster -Enode.name=node_1

环境变量配置

1
2
export HOSTNAME="host1,host2"
vim /opt/elasticsearch-7.14.0/config/elasticsearch.yml

写入

1
2
node.name:    ${HOSTNAME}
network.host: ${ES_NETWORK_HOST}

集群

配置

host8

host9

host10

查看

查看集群健康状态

http://192.168.2.8:9200/_cat/health`

查看集群节点

http://192.168.2.8:9200/_cat/nodes?pretty

其中 * 代表为 master 节点

elasticsearch.yml

host8

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
# 集群名称,在集群中不能重复,默认为 elasticsearch
cluster.name: my-cluster
# 集群节点描述
node.name: es-node8
# 集群角色,默认如下
# node.roles: ["master","data","data_content","data_hot","data_warm","data_cold","data_frozen","ingest","ml","remote_cluster_client","transform"]
# Add custom attributes to the node:
#node.attr.rack: r1
# data数据保存路径,默认为 elasticsearch/data
#path.data: /path/to/data
path:
data:
- /var/data/elasticsearch1
- /var/data/elasticsearch2
- /var/data/elasticsearch3
# 日志数据保存路径,默认为 elasticsearch/logs
#path.logs: /path/to/logs
logs:
- /var/log/elasticsearch1
- /var/log/elasticsearch2
- /var/log/elasticsearch3
# 绑定地址,所有人都可以访问
network.host: 192.168.2.8
# 绑定端口,用于外部通讯(9300端口:Tcp协议,ES集群之间的通讯)
http.port: 9200
# 集群发现
# The default list of hosts is ["127.0.0.1", "[::1]"]
discovery.seed_hosts: ["192.168.2.9", "192.168.2.10:9300"]
# 集群的节点,单机就写上面的节点名称,从当前节点中投票选出主节点
cluster.initial_master_nodes: ["es-node8","es-node9","es-node10"]
#bootstrap.memory_lock: true
# 删除索引时要求显式名称:
#action.destructive_requires_name: true

host9

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
# 集群名称,在集群中不能重复,默认为 elasticsearch
cluster.name: my-cluster
# 集群节点描述
node.name: es-node9
# 集群角色,默认如下
# node.roles: ["master","data","data_content","data_hot","data_warm","data_cold","data_frozen","ingest","ml","remote_cluster_client","transform"]
# Add custom attributes to the node:
#node.attr.rack: r1
# data数据保存路径,默认为 elasticsearch/data
#path.data: /path/to/data
path:
data:
- /var/data/elasticsearch1
- /var/data/elasticsearch2
- /var/data/elasticsearch3
# 日志数据保存路径,默认为 elasticsearch/logs
#path.logs: /path/to/logs
logs:
- /var/log/elasticsearch1
- /var/log/elasticsearch2
- /var/log/elasticsearch3
# 绑定地址,所有人都可以访问
network.host: 192.168.2.9
# 绑定端口,用于外部通讯(9300端口:Tcp协议,ES集群之间的通讯)
http.port: 9200
# 集群发现
# The default list of hosts is ["127.0.0.1", "[::1]"]
discovery.seed_hosts: ["192.168.2.8", "192.168.2.10:9300"]
# 集群的节点,单机就写上面的节点名称,从当前节点中投票选出主节点
cluster.initial_master_nodes: ["es-node8","es-node9","es-node10"]
#bootstrap.memory_lock: true
# 删除索引时要求显式名称:
#action.destructive_requires_name: true

host10

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
# 集群名称,在集群中不能重复,默认为 elasticsearch
cluster.name: my-cluster
# 集群节点描述
node.name: es-node10
# 集群角色,默认如下
# node.roles: ["master","data","data_content","data_hot","data_warm","data_cold","data_frozen","ingest","ml","remote_cluster_client","transform"]
# Add custom attributes to the node:
#node.attr.rack: r1
# data数据保存路径,默认为 elasticsearch/data
#path.data: /path/to/data
path:
data:
- /var/data/elasticsearch1
- /var/data/elasticsearch2
- /var/data/elasticsearch3
# 日志数据保存路径,默认为 elasticsearch/logs
#path.logs: /path/to/logs
logs:
- /var/log/elasticsearch1
- /var/log/elasticsearch2
- /var/log/elasticsearch3
# 绑定地址,所有人都可以访问
network.host: 192.168.2.10
# 绑定端口,用于外部通讯(9300端口:Tcp协议,ES集群之间的通讯)
http.port: 9200
# 集群发现
# The default list of hosts is ["127.0.0.1", "[::1]"]
discovery.seed_hosts: ["192.168.2.9", "192.168.2.8:9300"]
# 集群的节点,单机就写上面的节点名称,从当前节点中投票选出主节点
cluster.initial_master_nodes: ["es-node8","es-node9","es-node10"]
#bootstrap.memory_lock: true
# 删除索引时要求显式名称:
#action.destructive_requires_name: true

kibana.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# 端口
server.port: 5601
# 本机IP
server.host: "192.168.2.2"
#代理下指定一个路径挂载Kibana。
#使用服务器。rewriteBasePath的设置告诉Kibana是否应该删除basePath
#此设置不能以斜杠结束。
#server.basePath: ""
# 重写前缀为 server.basePath,默认为true.
#server.rewriteBasePath: false
# Specifies the public URL at which Kibana is available for end users. If
# `server.basePath` is configured this URL should end with the same basePath.
#server.publicBaseUrl: ""
# 请求最大负载大小
#server.maxPayload: 1048576
# 服务名称
#server.name: "your-hostname"
# Elasticsearch instances.
elasticsearch.hosts: ["http://192.168.2.2:9200"]

# Kibana使用Elasticsearch中的索引来存储已保存的搜索、可视化和仪表盘。Kibana创建一个新的索引,如果这个索引还不存在的话。
#kibana.index: ".kibana"
# 要加载的默认应用程序。
#kibana.defaultAppId: "home"
# 如果你的Elasticsearch受基本身份验证的保护,这些设置将提供Kibana服务器在启动时用于维护Kibana索引的用户名和密码。Kibana的用户仍然需要通过Elasticsearch进行身份验证,Elasticsearch是通过Kibana服务器代理的。
elasticsearch.username: "maxzhao"
elasticsearch.password: "maxzhao"
xpack.security.sessionTimeout: 600000
# 随机数长度大于32 https://www.elastic.co/guide/en/kibana/current/reporting-settings-kb.html
xpack.reporting.encryptionKey: "11112222333344445555666677778888"
# https://www.elastic.co/guide/en/kibana/6.x/using-kibana-with-security.html
xpack.security.encryptionKey: "11112222333344445555666677778888"
# 分别启用SSL和pem格式的SSL证书和SSL密钥文件的路径。
# 这些设置启用了从Kibana服务器向浏览器发送请求的SSL。
#server.ssl.enabled: false
#server.ssl.certificate: /path/to/your/server.crt
#server.ssl.key: /path/to/your/server.key

# Optional settings that provide the paths to the PEM-format SSL certificate and key files.
# These files are used to verify the identity of Kibana to Elasticsearch and are required when
# xpack.security.http.ssl.client_authentication in Elasticsearch is set to required.
#elasticsearch.ssl.certificate: /path/to/your/client.crt
#elasticsearch.ssl.key: /path/to/your/client.key

# Optional setting that enables you to specify a path to the PEM file for the certificate
# authority for your Elasticsearch instance.
#elasticsearch.ssl.certificateAuthorities: [ "/path/to/your/CA.pem" ]
# To disregard the validity of SSL certificates, change this setting's value to 'none'.
#elasticsearch.ssl.verificationMode: full

# Time in milliseconds to wait for Elasticsearch to respond to pings. Defaults to the value of
# the elasticsearch.requestTimeout setting.
#elasticsearch.pingTimeout: 1500

# Time in milliseconds to wait for responses from the back end or Elasticsearch. This value
# must be a positive integer.
#elasticsearch.requestTimeout: 30000

# List of Kibana client-side headers to send to Elasticsearch. To send *no* client-side
# headers, set this value to [] (an empty list).
#elasticsearch.requestHeadersWhitelist: [ authorization ]

# Header names and values that are sent to Elasticsearch. Any custom headers cannot be overwritten
# by client-side headers, regardless of the elasticsearch.requestHeadersWhitelist configuration.
#elasticsearch.customHeaders: {}

# Time in milliseconds for Elasticsearch to wait for responses from shards. Set to 0 to disable.
#elasticsearch.shardTimeout: 30000
# List of Kibana client-side headers to send to Elasticsearch. To send *no* client-side
# headers, set this value to [] (an empty list).
#elasticsearch.requestHeadersWhitelist: [ authorization ]

# Header names and values that are sent to Elasticsearch. Any custom headers cannot be overwritten
# by client-side headers, regardless of the elasticsearch.requestHeadersWhitelist configuration.
#elasticsearch.customHeaders: {}

# Time in milliseconds for Elasticsearch to wait for responses from shards. Set to 0 to disable.
#elasticsearch.shardTimeout: 30000

# Logs queries sent to Elasticsearch. Requires logging.verbose set to true.
#elasticsearch.logQueries: false

# Specifies the path where Kibana creates the process ID file.
#pid.file: /run/kibana/kibana.pid

# Enables you to specify a file where Kibana stores log output.
#logging.dest: stdout

# Set the value of this setting to true to suppress all logging output.
#logging.silent: false

# Set the value of this setting to true to suppress all logging output other than error messages.
#logging.quiet: false

# Set the value of this setting to true to log all events, including system usage information
# and all requests.
#logging.verbose: false

# Set the interval in milliseconds to sample system and process performance
# metrics. Minimum is 100ms. Defaults to 5000.
#ops.interval: 5000

# Specifies locale to be used for all localizable strings, dates and number formats.
# Supported languages are the following: English - en , by default , Chinese - zh-CN .
#i18n.locale: "en"

本文地址: https://github.com/maxzhao-it/blog/post/48916/

下载 HanLP

GitHub

这里下载的 hanlp-1.8.2-release.zip

配置

解压后,修改 hanlp.properties 中的 root 路径。

以及自定义词典文件的相对 root 的路径 CustomDictionaryPath

1
2
3
4
5
6
7
8
9
10
11
12
13
#本配置文件中的路径的根目录,根目录+其他路径=完整路径(支持相对路径,请参考:https://github.com/hankcs/HanLP/pull/254)
#Windows用户请注意,路径分隔符统一使用/
root=D:/develop/hanlp-1.8.2-release/HanLP

#好了,以上为唯一需要修改的部分,以下配置项按需反注释编辑。

#核心词典路径
#CoreDictionaryPath=data/dictionary/CoreNatureDictionary.txt
#2元语法词典路径
#BiGramDictionaryPath=data/dictionary/CoreNatureDictionary.ngram.txt
#自定义词典路径,用;隔开多个自定义词典,空格开头表示在同一个目录,使用“文件名 词性”形式则表示这个词典的词性默认是该词性。优先级递减。
#所有词典统一使用UTF-8编码,每一行代表一个单词,格式遵从[单词] [词性A] [A的频次] [词性B] [B的频次] ... 如果不填词性则表示采用词典的默认词性。
CustomDictionaryPath=data/dictionary/custom/CustomDictionary.txt; 现代汉语补充词库.txt; 全国地名大全.txt ns; 人名词典.txt; 机构名词典.txt; 上海地名.txt ns;data/dictionary/person/nrf.txt nrf;

Java 使用

Maven 引入

1
2
3
4
5
<dependency>
<groupId>com.hankcs</groupId>
<artifactId>hanlp</artifactId>
<version>portable-1.8.2</version>
</dependency>

代码

1
2
3
4
5
6
7
public class TestHanLP() {
@Test
public void testHanLP() {
List<Term> text = HanLP.segment("李四@擎天");
System.out.println(text);
}
}

没有配置自定义词典时,分词是 李,四,@,擎,天

添加词典

CustomDictionary.txt文件中添加

1
2
李四 nz 1
擎天 nz 1

此时要把 CustomDictionary.txt 同目录下的 CustomDictionary.txt.bin 删掉.

分词后的测试,是 李四,@,擎天 ,并且这个时候会发现,又生成了一个 CustomDictionary.txt.bin 文件。

本文地址: https://github.com/maxzhao-it/blog/post/23131/

介绍

Logstash 是一个自由和开放的服务器端数据处理管道吸入来自多种数据源的数据,转换,然后将其发送给你最喜欢的“储备”。

工作原理就是一种 输入->过滤->输出 的模式。

安装

下载

下载最新版本的Logstash压缩包

1
2
3
4
cd ~/
wget https://artifacts.elastic.co/downloads/logstash/logstash-8.4.1-linux-x86_64.tar.gz
tar -zxf logstash-8.4.1-linux-x86_64.tar.gz
mv logstash-8.4.1 logstash

启动

1
/opt/logstash/bin/logstash -e 'input { stdin { } } output { stdout {} }'

输出 Successfully started 表示启动成功。

命令里的-e表示后面跟着的是一个配置信息字符串,字符串的功能就是让 Logstash
接受控制台里的输入,并输出到控制台,比如在控制台输入 hello world :

如果用最简化的方式执行:

1
bin/logstash -e ""

输出

1
2
3
4
5
6
7
hello word!
{
"host" => "MAXZHAO-PC",
"message" => "hello word!\r",
"@version" => "1",
"@timestamp" => 2021-07-02T05:35:18.533Z
}

访问 端口默认为 9600

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"host": "MAXZHAO-PC",
"version": "7.13.2",
"http_address": "127.0.0.1:9600",
"id": "60d59feb-80eb-466a-97e0-d46d3fa75587",
"name": "MAXZHAO-PC",
"ephemeral_id": "758e9967-2f6f-49be-83b3-8e261e09446f",
"status": "green",
"snapshot": false,
"pipeline": {
"workers": 12,
"batch_size": 125,
"batch_delay": 50
},
"build_date": "2021-06-10T19:51:49Z",
"build_sha": "6d32f7df79a7d10d821b4cbff51c47f46d8c67b1",
"build_snapshot": false
}

配置

配置文件

实际运维中配置信息通常会放配置文件中来管理,这种情况下 Logstash 提供了 -f 参数来指定配置信息所在的配置文件。在 Logstash 的根目录下执行命令:

1
~/logstash/bin/logstash -f ~/logstash/config/logstash.conf

参考 config/logstash-sample.conf 创建config/logstash.conf , 内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
input {
stdin { }
}

output {
elasticsearch {
hosts => ["http://localhost:9200", "http://127.0.0.1:9200"]
index => "%{[@metadata][beat]}-%{[@metadata][version]}-%{+YYYY.MM.dd}"
#user => "elastic"
#password => "changeme"
}
stdout { }
file {
path => "D:\develop\logstash-7.13.2\data-demo\%{type}.%{+yyyy.MM.dd.HH}.txt"
}
}

在启动的控制台输入 hello,则控制台会输出 hello,并且文件也会写入 hello

使用

logstash 在输入、过滤、输出都是由很多插件配合。

官方的插件文档

插件配置

value types

Array

: list = > true

1
users => [ {id => 1, name => bob}, {id => 2, name => jane} ]
List

不是类型本身,而是属性类型可以具有。这使得输入检查多个值成为可能。插件作者可以通过在声明参数时指定: list = > true 来启用列表检查。

1
2
path => [ "/var/log/messages", "/var/log/*.log" ]
uris => [ "http://elastic.co", "http://example.net" ]

此示例将 path 配置为一个包含三个字符串中每个字符串的元素的列表。它还将 URIs 参数配置为 uri 列表,如果提供的任何 uri 无效,则失败。

Boolean
1
ssl_enable => true
Bytes
1
2
3
4
my_bytes => "1113"   # 1113 bytes
my_bytes => "10MiB" # 10485760 bytes
my_bytes => "100kib" # 102400 bytes
my_bytes => "180 mb" # 180000000 bytes
Codec

编码解码器是用来表示数据的 Logstash 编码解码器的名称。编解码器可以用于输入和输出。

输入解码器提供了一种在数据进入输入之前对其进行解码的方便方法。输出解码器提供了一种在数据离开输出之前对其进行编码的方便方法。使用输入或输出编码解码器可以避免在 Logstash 管道中使用单独的过滤器。

1
codec => "json"

Hash

多个键值项之间用空格而不是逗号分隔。

1
2
3
4
5
6
7
match => {
"field1" => "value1"
"field2" => "value2"
...
}
# or as a single line. No commas between entries:
match => { "field1" => "value1" "field2" => "value2" }

Number

数字必须是有效的数值(浮点数或整数)。

1
port => 33

Password

密码是一个字符串,其中包含一个未记录或打印的值。

1
my_password => "password"

URI

一个 URI 可以是任何东西,从一个完整的 URL,如 http://elastic.co/地址,到一个简单的标识符,如 foobar。如果 URI 包含一个密码,比如 http://user:pass@example.net ,那么 URI 的密码部分将不会被记录或打印。

1
my_uri => "http://foo:bar@example.net"
Path

路径是表示有效操作系统路径的字符串。

1
my_path => "/tmp/logstash"
String

字符串必须是单个字符序列。注意,字符串值用引号括起来,可以是双引号,也可以是单引号。

Escape Sequences

转移符号

Text文字 Result结果
\r carriage return (ASCII 13)回车符
\n new line (ASCII 10)
\t tab (ASCII 9)
\\ backslash (ASCII 92)反斜杠
\" double quote (ASCII 34)
\' single quote (ASCII 39)
1
2
name => "Hello world"
name => 'It\'s a beautiful day'

插件安装

插件安装

安装插件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 查看
/opt/logstash/bin/logstash-plugin list
# 在线安装
/opt/logstash/bin/logstash-plugin install logstash-filter-grok
vim /opt/logstash/Gemfile
# 更新
/opt/logstash/bin/logstash-plugin update logstash-filter-grok
mkdir /opt/logstash/plugins
cd /opt/logstash/plugins
wget https://github.com/logstash-plugins/logstash-filter-grok/archive/refs/tags/v4.4.2.tar.gz
tar -zxvf v4.4.2.tar.gz
vim /opt/logstash/Gemfile
# 写入
# gem "logstash-filter-grok", :path => "path"

input-file 插件

看下 input 的一个插件例子。上面讲的是从控制台输入,如果要从文件读取输入,则可以用 file 插件:

1
input { file { path => "/tmp/abc.log" }}

上面是这个插件的最小化配置, path 后面跟随的是文件的全路径名,如果要匹配一个目录下的所有文件,可以用通配符*:

1
input { file { path => "/tmp/data/*" } }

要匹配多个不同目录下的文件,则用中括号括起来,并逗号分隔不同文件路径:

1
input { file { path => ["/tmp/data/*","/log/abc/hello.log"] }}

注意文件的路径名需要时绝对路径。

output-elasticsearch 插件

如果要将数据输出到,则可以用 Elasticsearch 插件:

1
2
3
4
5
6
7
output {
elasticsearch {
action => "index"
hosts => "localhost:9200"
index => "log-example"
}
}

上面配置的含义是,将数据输出到 Elasticsearch 服务器,hosts 是提供服务的地址和端口号,action 是指索引到一个文档,index 是指要被写进的索引名,当然还有其他参数配置,具体参见该插件的官方文档说明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
input {
stdin { }
}

output {
stdout { }
file {
path => "D:\develop\logstash-7.13.2\data-demo\%{type}.%{+yyyy.MM.dd.HH}.txt"
}
elasticsearch {
#action => "%{[@metadata][action]}"
#document_id => "%{[@metadata][_id]}"
hosts => ["http://localhost:9200"]
index => "logstash"
#protocol => "http"
#hosts => ["http://localhost:9200", "http://127.0.0.1:9200"]
#index => "%{[@metadata][beat]}-%{[@metadata][version]}-%{+YYYY.MM.dd}"
#user => "elastic"
#password => "changeme"
}
}

filter-grok 插件

不论是 input 的 stdin 还是 file 插件,都是从不同来源读取数据,但它们读取的都是一行一行的文本数据,输出的时候会发现它们都是作为一行放到输出的 message 属性中:

img

文本输出

很多情况下需要对这些文本做格式化的解析再输出,比如日志文件中数据格式是这样的:

1
[2017-04-03 23:30:11.020][INFO][logstash] Pipeline main started

上面的文本格式是:[时间][日志级别][模块名]日志信息描述
输出 json 时也希望将时间放到自定义的 TimeStamp 属性中,将日志级别信息放到
LogLevel 属性中,将模块名放到 ModuleName 属性中,将日志信息描述放到
LogDesc 属性中。

如果是这种需求就用到了 grok 插件,该插件是 Logstash 将普通文本解析成结构化数据的最好的方式。(这可不是我非要安利,是官网上说的:Grok is currently the best way in logstash to parse crappy unstructured log data into something structured and queryable.)

  1. grok 表达式
    grok 表达式语法是这样的:
1
%{SYNTAX:SEMANTIC}

SYNTAX 是要匹配的文本的模式名。SEMANTIC 是匹配出的内容的标识符,该标识符即输出到 output 中的属性名。看一个简单的 grok 表达式例子:

1
%{IP:source_ip}

它表示使用名为 IP 的正则表达式提取内容,并将匹配出的内容命名为 source_ip 。所以如果输入是 IP 地址的格式:11.22.33.123,则会将该内容放到 source_ip 中。

  1. grok 中预定义的模式
    上面的 IP 是 grok 里预定义的模式,其正则表达式的定义实际是:

    img

    IP 模式定义

    grok 已经预定义了很多模式,比如匹配一串数字可以用 NUMBER、匹配 MAC 地址用 MAC、匹配时间用 TIMESTAMP_ISO8601、匹配 LOG 日志级别用 LOGLEVEL

    等等。详细定义参见

    github 中的说明

  2. grok 中的自定义模式
    如果上面列的这些模式不能满足需求,grok 也允许自定义模式。
    先看下自定义模式的语法:

1
pattern_name regexp

pattern_name 就是自定义的模式名,regexp 就是模式的正则表达式定义,之间用一个空格分隔开。比如自定义一个队列 ID 模式,它的格式是10或11个数字、大写字母组成的字符串,其定义语法如下:

1
QUEUE_ID [0-9A-F]{10,11}

熟悉正则表达是的应该知道[0-9A-F]表示数字、大写字母组成的字符,后面的{10,11}表示有10或11个这样的字符。
接着在 Logstash 根目录下建一个 patterns 目录,该目录下新建一个文件叫
myPattern 。文件内容就是:

1
QUEUE_ID [0-9A-F]{10,11}

最后在 filter 配置中加上 patterns 目录,并引用上面定义的这个 QUEUE_ID :

1
2
3
4
5
6
filter {
grok {
patterns_dir => ["./patterns"]
match => { "message" => "%{TIMESTAMP_ISO8601:TimeStamp} %{QUEUE_ID:queue_id}: %{GREEDYDATA:syslog_message}" }
}
}

patterns_dir 用于指定自定义模式的文件所在的目录,match 的内容就是 grok 表达式,TIMESTAMP_ISO8601 和 GREEDYDATA 预定义的模式,QUEUE_ID 是自定义的模式。它将匹配以下格式的内容:

1
2017-04-03 23:30:11.020 12345abcde hello world

匹配后的结果是:

1
{"@timestamp": "2017-04-12T11:57:40.186Z",  "queue_id": "12345abcde",  "@version": "1",  "syslog_message": "hello world",  "message": "2017-04-03 23:30:11.020 12345abcde hello world",  "TimeStamp": "2017-04-03 23:30:11.020"}
  1. 日志文件的 filter 配置
    所以上面的日志文件中数据的 filter 区段配置:
1
2
3
4
5
6
7
filter {
grok {
match => {
"message" => "\[%{TIMESTAMP_ISO8601:TimeStamp}\]\[%{LOGLEVEL:LogLevel}\]\[%{WORD:ModuleName}\] %{GREEDYDATA:LogDesc}"
}
}
}

由于中括号是特殊字符,所以正则表达式中它的前面要加上反斜杠\。
加载文件配置后运行结果如下:

img

本文地址: https://github.com/maxzhao-it/blog/post/9074/

RabbitMQ是一个免费的开源企业消息代理软件。 它是用Erlang编写的,并实现了高级消息队列协议(AMQP)。 它提供所有主要编程语言的客户端库。 它支持多种消息传递协议,消息队列,传送确认,灵活的路由到队列,多种交换类型。 它还提供易于使用的HTTP-API,命令行工具和用于管理RabbitMQ的Web UI;

在当前文档中,我们将在CentOS 7服务器上安装RabbitMQ。

注意:erlang-24.x已经不支持 CentOS7

rpm 安装

安装 RabbitMQ需要安装Erlang

Erlanghttps://github.com/rabbitmq/erlang-rpm/releases
RabbitMQhttps://github.com/rabbitmq/rabbitmq-server/releases

RabbitMQErlang版本对应关系 https://www.rabbitmq.com/which-erlang.html

我这里下载了

1
2
3
4
5
6
7
8
# 安装依赖
rpm -ivh openssl-libs-1.0.2k-25.el7_9.x86_64.rpm --force
# 安装环境
rpm -ivh erlang-22.3.4.21-1.el7.x86_64.rpm
# 验证erlang 是否安装成功
erl -version
# 安装 RabbitMQ
rpm -ivh rabbitmq-server-3.9.15-1.el7.noarch.rpm

配置启动

安装web管理界面

1
2
3
sudo rabbitmq-plugins enable rabbitmq_management
# 查看所有的插件
sudo rabbitmq-plugins list

启动

1
2
3
4
5
6
# 设置开机自启服务
systemctl enable rabbitmq-server
# 启动RabbitMQ
systemctl start rabbitmq-server
# 重启
systemctl restart rabbitmq-server

配置文件

1
vim /etc/rabbitmq/rabbitmq.config

安装好之后在/usr/share/doc/rabbitmq-server-3.6.15/有参考模板rabbitmq.config.example

配置端口,备注:消息端口5672,则web访问端口为 15672

1
2
3
4
5
6
7
8
[
{rabbit,
[
{loopback_users, []},
{tcp_listeners, [5672]}
]
}
]

参考模板

其它管理

用户管理

1
2
3
4
5
6
7
8
9
10
11
12
# 修改guest的密码
sudo rabbitmqctl list_users
sudo rabbitmqctl change_password guest guest

# 创建其他管理员账号比如test/test:
sudo rabbitmqctl add_user maxzhao maxzhao
#
sudo rabbitmqctl set_user_tags maxzhao administrator
# /是 vhost的目录 Configure regexp Write regexp Read regexp
sudo rabbitmqctl set_permissions -p / maxzhao ".*" ".*" ".*"
# Sets user topic permissions for an exchange,默认使用 AMQP default 的exchange
# sudo rabbitmqctl set_topic_permissions

添加vhost

1
2
3
4
5
6
7
8
9
10
11
# 查看帮助
sudo rabbitmqctl --help
# 查看创建 vhost 的帮助
sudo rabbitmqctl add_vhost --help
# 创建
sudo rabbitmqctl add_vhost maxzhao_vhost
# 查看
sudo rabbitmqctl list_vhosts
# 赋权 注意 /maxzhao_vhost 与 maxzhao_vhost 不一样
sudo rabbitmqctl set_permissions -p /maxzhao_vhost maxzhao ".*" ".*" ".*"

删除 vhost

1
2
sudo rabbitmqctl add_vhost maxzhaoTest
sudo rabbitmqctl delete_vhost maxzhaoTest

Yum 安装

安装Erlang

RabbitMQ是用Erlang语言编写的,在本教程中我们将安装最新版本的Erlang到服务器中。 Erlang在默认的YUM存储库中不可用,因此您将需要安装EPEL存储库。 运行以下命令相同。

1
2
yum -y install epel-release 
yum -y update

现在使用以下命令安装Erlang。

1
yum -y install erlang socat logrotate 

您现在可以使用以下命令检查Erlang版本。

1
erl -version

您将得到以下输出。

1
Eshell V5.19.4

Erlang (ASYNC_THREADS,HIPE) (BEAM) emulator version 5.10.4
要切换到Erlang shell,可以键入以下命令。
erl
shell将更改,您将得到以下输出。
Erlang R16B03-1 (erts-5.10.4) [source] [64-bit] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V5.10.4 (abort with ^G)
1>
您可以通过按ctrl + C两次退出shell。 Erlang现在安装在系统上,现在可以继续安装RabbitMQ。

安装RabbitMQ

1
wget https://github.com/rabbitmq/rabbitmq-server/releases/download/v3.9.0/rabbitmq-server-3.9.0-1.el7.noarch.rpm

这里可以随时找到最新版本的RabbitMQ下载页面的链接。

通过运行导入GPG密钥:

1
2
3
4
5
6
## primary RabbitMQ signing key
rpm --import https://github.com/rabbitmq/signing-keys/releases/download/2.0/rabbitmq-release-signing-key.asc
## modern Erlang repository
rpm --import https://packagecloud.io/rabbitmq/erlang/gpgkey
## RabbitMQ server repository
rpm --import https://packagecloud.io/rabbitmq/rabbitmq-server/gpgkey

安装MQ

1
rpm -Uvh rabbitmq-server-3.9.0-1.el7.noarch.rpm 

启动

您可以通过运行以下命令启动RabbitMQ服务器进程。

1
systemctl start rabbitmq-server

要在引导时自动启动RabbitMQ,请运行以下命令。

1
systemctl enable rabbitmq-server

要检查RabbitMQ服务器的状态,请运行:

1
systemctl status rabbitmq-server

配置源 rabbitmq.repo

1
yum update -y

安装

1
2
yum install socat logrotate -y
yum install erlang rabbitmq-server -y

rabbitmq.repo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
##
## Zero dependency Erlang
##

[rabbitmq_erlang]
name=rabbitmq_erlang
baseurl=https://packagecloud.io/rabbitmq/erlang/el/7/$basearch
repo_gpgcheck=1
gpgcheck=1
enabled=1
# PackageCloud's repository key and RabbitMQ package signing key
gpgkey=https://packagecloud.io/rabbitmq/erlang/gpgkey
https://github.com/rabbitmq/signing-keys/releases/download/2.0/rabbitmq-release-signing-key.asc
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt
metadata_expire=300

[rabbitmq_erlang-source]
name=rabbitmq_erlang-source
baseurl=https://packagecloud.io/rabbitmq/erlang/el/7/SRPMS
repo_gpgcheck=1
gpgcheck=0
enabled=1
gpgkey=https://packagecloud.io/rabbitmq/erlang/gpgkey
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt
metadata_expire=300

##
## RabbitMQ server
##

[rabbitmq_server]
name=rabbitmq_server
baseurl=https://packagecloud.io/rabbitmq/rabbitmq-server/el/7/$basearch
repo_gpgcheck=1
gpgcheck=1
enabled=1
# PackageCloud's repository key and RabbitMQ package signing key
gpgkey=https://packagecloud.io/rabbitmq/rabbitmq-server/gpgkey
https://github.com/rabbitmq/signing-keys/releases/download/2.0/rabbitmq-release-signing-key.asc
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt
metadata_expire=300

[rabbitmq_server-source]
name=rabbitmq_server-source
baseurl=https://packagecloud.io/rabbitmq/rabbitmq-server/el/7/SRPMS
repo_gpgcheck=1
gpgcheck=0
enabled=1
gpgkey=https://packagecloud.io/rabbitmq/rabbitmq-server/gpgkey
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt
metadata_expire=300

离线安装获取全部依赖

1
2
3
4
mkdir ~/docker
sudo yum install --downloadonly --downloaddir=/home/maxzhao/erlang/ erlang
sudo yum install --downloadonly --downloaddir=/home/maxzhao/rabbitmq/ rabbitmq-server
sudo yum localinstall /home/maxzhao/erlang/*.rpm

已经安装可以使用 reinstall

本文地址: https://github.com/maxzhao-it/blog/post/21590/

介绍

Elasticsearch是位于Elastic Stack核心的分布式搜索和分析引擎,是一个基于Apache Lucene(TM)的开源搜索引擎,无论在开源还是专有领域,Lucene可以被认为是迄今为止最先进、性能最好的、功能最全的搜索引擎库。
但是,Lucene只是一个库。想要发挥其强大的作用,你需使用Java并要将其集成到你的应用中。Lucene非常复杂,你需要深入的了解检索相关知识来理解它是如何工作的。

LogstashBeats有助于收集、聚合和丰富数据,并将其存储在Elasticsearch中。Kibana使您能够交互式地探索、可视化和共享对数据的见解,并管理和监控堆栈。Elasticsearch是索引、搜索和分析魔术发生的地方。

Elasticsearch也是使用Java编写并使用Lucene来建立索引并实现搜索功能,但是它的目的是通过简单连贯的RESTful API让全文搜索变得简单并隐藏Lucene复杂性。
不过,Elasticsearch不仅仅是Lucene和全文搜索引擎,它还提供:

  • 分布式的实时文件存储,每个字段都被索引并可被搜索
  • 实时分析的分布式搜索引擎
  • 可以扩展到上百台服务器,处理PB级结构化或非结构化数据

虽然不是每个问题都是搜索问题,但Elasticsearch提供了在各种用例中处理数据的速度和灵活性:

  • 在应用程序或网站中添加搜索框

  • 存储和分析日志、指标和安全事件数据

  • 使用机器学习来自动模拟实时数据的行为

  • 使用Elasticsearch作为存储引擎实现业务工作流的自动化

  • 使用Elasticsearch作为地理信息系统(GIS)管理、集成和分析空间信息

  • 使用Elasticsearch作为生物信息学研究工具存储和处理遗传数据

附上官网地址

安装

2022-10-01 更新至 8.4.1

2023-01-15 更新至 8.6.0

解压安装

添加用户

1
2
3
4
5
6
7
8
9
10
11
12
# 添加账号
useradd es
# 修改密码
passwd es
# 把用户加入到 root 组
usermod -aG es root
sudo yum install -y wget
# 加入到 sudo 中
sudo vim /etc/sudoers
# 添加一行: es ALL=(ALL) ALL
su es
sudo chown es ./

Centos 系统配置

max file

修改

1
sudo vim /etc/security/limits.conf

添加

1
2
3
4
* soft nofile 65536
* hard nofile 65536
* soft nproc 65536
* hard nproc 65536

执行

1
2
sudo source /etc/security/limits.conf
ulimit -a

virtual memory

1
2
3
4
# 添加 一行 vm.max_map_count=655360
sudo echo 'vm.max_map_count=655360' >> /etc/sysctl.conf
# 重新加载参数
sysctl -p

下载

下载地址 or ES start

下载

1
2
3
4
5
cd /home/es/
mkdir tools && cd tools
wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-8.6.0-linux-x86_64.tar.gz
wget -b https://artifacts.elastic.co/downloads/kibana/kibana-8.6.0-linux-x86_64.tar.gz
wget -b https://artifacts.elastic.co/downloads/logstash/logstash-8.6.0-linux-x86_64.tar.gz

解压

1
2
3
4
5
cd /home/es/
tar -zxf /home/es/tools/elasticsearch-8.6.0-linux-x86_64.tar.gz -C /home/es/
tar -zxf /home/es/tools/kibana-8.6.0-linux-x86_64.tar.gz -C /home/es/
mv /home/es/elasticsearch-8.6.0 /home/es/elasticsearch
mv /home/es/kibana-8.6.0 /home/es/kibana

核心配置

ElasticSearch

配置证书

1
2
3
4
5
6
7
8
/home/es/elasticsearch/bin/elasticsearch-certutil ca
#Please enter the desired output file [elastic-stack-ca.p12]: 输入名称
#Enter password for elastic-stack-ca.p12 : 输入密码
/home/es/elasticsearch/bin/elasticsearch-certutil cert --ca elastic-stack-ca.p12
#Enter password for CA (elastic-stack-ca.p12) : 输入上面的密码
#Please enter the desired output file [elastic-certificates.p12]: 输入当前节点的名称
#Enter password for elastic-certificates.p12 : 输入当前节点的密码
mv /home/es/elasticsearch/elastic-certificates.p12 /home/es/elasticsearch/config/

备份

1
cp /home/es/elasticsearch/config/elasticsearch.yml  /home/es/elasticsearch/config/elasticsearch.yml-bak

修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

cat > /home/es/elasticsearch/config/elasticsearch.yml <<EOF
# 集群名称,在集群中不能重复,默认为 elasticsearch
cluster.name: cluster1
# 集群节点描述
node.name: es-node1
#node.attr.rack: r1
# data数据保存路径,默认为 elasticsearch/data
#path.data: /path/to/data
# 日志数据保存路径,默认为 elasticsearch/logs
#path.logs: /path/to/logs
#bootstrap.memory_lock: true
# 绑定地址,所有人都可以访问
network.host: 0.0.0.0
# 绑定端口,用于外部通讯(9300端口:Tcp协议,ES集群之间的通讯)
http.port: 49200
transport.port: 49300
#discovery.seed_hosts: ["host1", "host2"]
# 集群的节点,单机就写上面的节点名称
cluster.initial_master_nodes: ["es-node1"]
#readiness.port: 9399
#action.destructive_requires_name: false
# Enable security features
xpack.security.enabled: true
xpack.security.enrollment.enabled: false
# Enable encryption for HTTP API client connections, such as Kibana, Logstash, and Agents
xpack.security.http.ssl:
# 关闭 ssl
enabled: false
# keystore.path: certs/http.p12
# Enable encryption and mutual authentication between cluster nodes
xpack.security.transport.ssl:
enabled: true
verification_mode: certificate
keystore.path: elastic-certificates.p12
truststore.path: elastic-certificates.p12
EOF
cat /home/es/elasticsearch/config/elasticsearch.yml

Kibana

复制配置

1
cp  /home/es/kibana/config/kibana.yml  /home/es/kibana/config/kibana.yml-bak 

修改配置

1
2
3
4
5
6
7
8
9
10
11
12
13
cat > /home/es/kibana/config/kibana.yml <<EOF
server.port: 45601
server.host: "192.168.15.68"
server.name: "kibana-host2"
# 代理配置
# server.basePath: "/kibana"
# server.rewriteBasePath: true
elasticsearch.hosts: ["http://192.168.15.68:49200"]
elasticsearch.username: "maxzhao"
elasticsearch.password: "maxzhao."
i18n.locale: "zh-CN"
EOF
cat /home/es/kibana/config/kibana.yml

启动

1
2
3
/home/es/elasticsearch/bin/elasticsearch -d -p 88888
tail -f /home/es/elasticsearch/logs/cluster1.log
/home/es/kibana/bin/kibana

初始化ES密码

1
2
3
4
5
6
7
8
9
10
11
12
13

# 重置
/home/es/elasticsearch/bin/elasticsearch-reset-password --url "http://127.0.0.1:49200" --username elastic -i
# 测试重置后的密码
curl -u elastic:elastic. 127.0.0.1:49200
# 重置全部
/home/es/elasticsearch/bin/elasticsearch-setup-passwords interactive
# 查看用户
/home/es/elasticsearch/bin/elasticsearch-users list
# 新增用户
/home/es/elasticsearch/bin/elasticsearch-users useradd maxzhao -p maxzhao. -r apm_system
# 添加角色
/home/es/elasticsearch/bin/elasticsearch-users roles maxzhao -r apm_system -a apm_system,watcher_admin,viewer,logstash_system,rollup_user,kibana_user,beats_admin,remote_monitoring_agent,rollup_admin,snapshot_user,data_frame_transforms_admin,monitoring_user,enrich_user,kibana_admin,logstash_admin,editor,data_frame_transforms_user,machine_learning_user,machine_learning_admin,watcher_user,apm_user,beats_system,transform_user,reporting_user,kibana_system,transform_admin,remote_monitoring_collector,transport_client,ingest_admin,superuser
1
2
3
4
5
6
/home/es/elasticsearch/bin/elasticsearch-users
([useradd <username>] [-p <password>] [-r <roles>]) |
([list] <username>) |
([passwd <username>] [-p <password>]) |
([roles <username>] [-a <roles>] [-r <roles>]) |
([userdel <username>])

访问

  1. 访问ES http://127.0.0.1:49200/
  2. 访问kibana http://localhost:45601

后台启动

1
2
3
/home/es/elasticsearch/bin/elasticsearch -d -p 88888
nohup /home/es/kibana/bin/kibana >> kibana.log 2>&1 &
tail -f kibana.log

停止服务

1
2
3
4
5
ps -ef|grep elasticsearch
ps -ef|grep kibana
kill -9 xxx
# 一键
ps -ef|grep '/kibana' | grep -v grep |awk '{print $2}' |xargs -I {} kill '{}'

启动方式

指定进程ID

进程ID写在文件中,方便关闭

1
2
/home/es/elasticsearch/bin/elasticsearch -d -p 88888
pkill -F 88888

外部化配置

1
/home/es/elasticsearch/bin/elasticsearch -d -Ecluster.name=my_cluster -Enode.name=node_1

环境变量配置

1
2
export HOSTNAME="host1,host2"
vim /home/es/elasticsearch/config/elasticsearch.yml

写入

1
2
node.name:    ${HOSTNAME}
network.host: ${ES_NETWORK_HOST}

开机自启

1
vim /etc/rc.d/rc.local

写入

1
2
su es -c "/home/es/elasticsearch/bin/elasticsearch -d -p 88888"
su es -c "nohup /home/es/kibana/bin/kibana >> kibana.log 2>&1 &"

安装ES插件

1
2
3
4
# 地理位置
/home/es/elasticsearch/bin/elasticsearch-plugin install
# 浏览器信息
/home/es/elasticsearch/bin/elasticsearch-plugin install

配置

1. ES 目录介绍

  1. bin:可执行脚本文件,包含ES的启动脚本
  2. config:配置文件目录
  3. JDK: java环境
  4. lib:依赖的jar,类库
  5. logs:日志文件
  6. modules:ES相关模块
  7. plugins:插件位置
  8. data:自定义的索引存储目录

2. 核心配置文件

elasticsearch/config/elasticsearch.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 集群名称,在集群中不能重复,默认为  elasticsearch
cluster.name: cluster1
# 集群节点描述
node.name: es-node1
# data数据保存路径,默认为 elasticsearch/data
#path.data: /path/to/data
# 日志数据保存路径,默认为 elasticsearch/logs
#path.logs: /path/to/logs
# 绑定地址,所有人都可以访问
network.host: 0.0.0.0
# 绑定端口,用于外部通讯(9300端口:Tcp协议,ES集群之间的通讯)
http.port: 9200
# 集群的节点,单机就写上面的节点名称
cluster.initial_master_nodes: ["es-node1"]

3. 添加用户

Linux 下 ES不允许使用 root 操作 ,需要添加用户。

4.1 生成ES的秘钥

4.1.1 生成根密钥

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[root@localhost bin]# ./elasticsearch-certutil ca --pem
future versions of Elasticsearch will require Java 11; your Java version from [/opt/module/haoke/jdk1.8.0_141/jre] does not meet this requirement
This tool assists you in the generation of X.509 certificates and certificate
signing requests for use with SSL/TLS in the Elastic stack.

The 'ca' mode generates a new 'certificate authority'
This will create a new X.509 certificate and private key that can be used
to sign certificate when running in 'cert' mode.

Use the 'ca-dn' option if you wish to configure the 'distinguished name'
of the certificate authority

By default the 'ca' mode produces a single PKCS#12 output file which holds:
* The CA certificate
* The CA's private key

If you elect to generate PEM format certificates (the -pem option), then the output will
be a zip file containing individual files for the CA certificate and private key

Please enter the desired output file [elastic-stack-ca.zip]:

4.1.2 解压根秘钥

1
2
3
4
5
6
7
8
[root@localhost bin]# unzip elastic-stack-ca.zip 
Archive: elastic-stack-ca.zip
creating: ca/
inflating: ca/ca.crt
inflating: ca/ca.key
总用量 8
-rw-r--r--. 1 root root 1200 327 19:43 ca.crt
-rw-r--r--. 1 root root 1679 327 19:43 ca.key

4.1.3 生成节点秘钥

1
[root@localhost bin]# ./elasticsearch-certutil cert --ca-cert ca/ca.crt --ca-key ca/ca.key --pem

4.1.4 解压节点密钥

1
[root@localhost bin]# unzip certificate-bundle.zip

4.1.5 自定义配置路径

1
2
[root@localhost bin]# cd /usr/local/elasticsearch-7.4.2/config
[root@localhost config]# mkdir x-pack

bin目录生成的ca和instance两个文件夹 拷贝至config下面的x-pack文件夹下

4.2 配置秘钥

1
[root@localhost config]# vi elasticsearch.yml

最后添加如下代码:

1
2
3
4
5
6
7
xpack.security.enabled: true
xpack.security.transport.ssl.enabled: true
xpack.ssl.key: x-pack/instance/instance.key
xpack.ssl.certificate: x-pack/instance/instance.crt
xpack.ssl.certificate_authorities: x-pack/ca/ca.crt
xpack.ssl.verification_mode: certificate
xpack.ssl.client_authentication: required

4.3 重新启动ES

4.3.1 停止服务

1
2
3
4
[root@localhost config]# jps
28696 Elasticsearch
29977 Jps
[root@localhost config]# kill 28696

4.3.2 启动服务

1
2
[root@localhost bin]# cd /usr/local/elasticsearch-7.4.2/bin
[root@localhost bin]# ./elasticsearch -d

4.4 设置密码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[root@localhost bin]# ./elasticsearch-setup-passwords interactive
future versions of Elasticsearch will require Java 11; your Java version from [/opt/module/haoke/jdk1.8.0_141/jre] does not meet this requirement
Initiating the setup of passwords for reserved users elastic,apm_system,kibana,logstash_system,beats_system,remote_monitoring_user.
You will be prompted to enter passwords as the process progresses.
Please confirm that you would like to continue [y/N]y

Enter password for [elastic]:
Reenter password for [elastic]:
Enter password for [apm_system]:
Reenter password for [apm_system]:
Enter password for [kibana]:
Reenter password for [kibana]:
Enter password for [logstash_system]:
Reenter password for [logstash_system]:
Enter password for [beats_system]:
Reenter password for [beats_system]:
Enter password for [remote_monitoring_user]:
Reenter password for [remote_monitoring_user]:
Changed password for user [apm_system]
Changed password for user [kibana]
Changed password for user [logstash_system]
Changed password for user [beats_system]
Changed password for user [remote_monitoring_user]
Changed password for user [elastic]

问题:

max file descriptors [4096] for elasticsearch process is too low

修改

1
sudo vim /etc/security/limits.conf

添加

1
2
3
4
* soft nofile 65536
* hard nofile 65536
* soft nproc 65536
* hard nproc 65536

执行

1
sudo source /etc/security/limits.conf

max ``virtual memory areas vm.max_map_count [65530] ``is too low, increase to at least [262144]

1
2
3
4
sudo vim  /etc/sysctl.conf  
# 添加 一行 vm.max_map_count=655360
# 重新加载参数
sudo sysctl -p

 注意:使用docker或者k8s启动报该错误修改宿主机或者node的该参数,而不是修改容器镜像的该参数。

elasticsearch.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
# 集群名称,在集群中不能重复,默认为 elasticsearch
cluster.name: my-cluster
# 集群节点描述
node.name: es-node1
# 集群角色,默认如下
# node.roles: ["master","data","data_content","data_hot","data_warm","data_cold","data_frozen","ingest","ml","remote_cluster_client","transform"]
# Add custom attributes to the node:
#node.attr.rack: r1
# data数据保存路径,默认为 elasticsearch/data
#path.data: /path/to/data
path:
data:
- /var/data/elasticsearch
- /var/data/elasticsearch
- /var/data/elasticsearch
# 日志数据保存路径,默认为 elasticsearch/logs
#path.logs: /path/to/logs
log:
- /var/log/elasticsearch
- /var/log/elasticsearch
- /var/log/elasticsearch
# 绑定地址,所有人都可以访问
network.host: 192.168.2.8
# 绑定端口,用于外部通讯(9300端口:Tcp协议,ES集群之间的通讯)
http.port: 9200
# 集群发现
# The default list of hosts is ["127.0.0.1", "[::1]"]
discovery.seed_hosts: ["192.168.2.9", "192.168.2.10:9300"]
# 集群的节点,单机就写上面的节点名称,从当前节点中投票选出主节点
cluster.initial_master_nodes: ["es-node1"]
#bootstrap.memory_lock: true
# 删除索引时要求显式名称:
#action.destructive_requires_name: true

kibana.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# 端口
server.port: 5601
# 本机IP
server.host: "192.168.2.2"
#代理下指定一个路径挂载Kibana。
#使用服务器。rewriteBasePath的设置告诉Kibana是否应该删除basePath
#此设置不能以斜杠结束。
#server.basePath: ""
# 重写前缀为 server.basePath,默认为true.
#server.rewriteBasePath: false
# Specifies the public URL at which Kibana is available for end users. If
# `server.basePath` is configured this URL should end with the same basePath.
#server.publicBaseUrl: ""
# 请求最大负载大小
#server.maxPayload: 1048576
# 服务名称
#server.name: "your-hostname"
# Elasticsearch instances.
elasticsearch.hosts: ["http://192.168.2.2:9200"]

# Kibana使用Elasticsearch中的索引来存储已保存的搜索、可视化和仪表盘。Kibana创建一个新的索引,如果这个索引还不存在的话。
#kibana.index: ".kibana"
# 要加载的默认应用程序。
#kibana.defaultAppId: "home"
# 如果你的Elasticsearch受基本身份验证的保护,这些设置将提供Kibana服务器在启动时用于维护Kibana索引的用户名和密码。Kibana的用户仍然需要通过Elasticsearch进行身份验证,Elasticsearch是通过Kibana服务器代理的。
elasticsearch.username: "maxzhao"
elasticsearch.password: "maxzhao"
xpack.security.sessionTimeout: 600000
# 随机数长度大于32 https://www.elastic.co/guide/en/kibana/current/reporting-settings-kb.html
xpack.reporting.encryptionKey: "11112222333344445555666677778888"
# https://www.elastic.co/guide/en/kibana/6.x/using-kibana-with-security.html
xpack.security.encryptionKey: "11112222333344445555666677778888"
# 分别启用SSL和pem格式的SSL证书和SSL密钥文件的路径。
# 这些设置启用了从Kibana服务器向浏览器发送请求的SSL。
#server.ssl.enabled: false
#server.ssl.certificate: /path/to/your/server.crt
#server.ssl.key: /path/to/your/server.key

# Optional settings that provide the paths to the PEM-format SSL certificate and key files.
# These files are used to verify the identity of Kibana to Elasticsearch and are required when
# xpack.security.http.ssl.client_authentication in Elasticsearch is set to required.
#elasticsearch.ssl.certificate: /path/to/your/client.crt
#elasticsearch.ssl.key: /path/to/your/client.key

# Optional setting that enables you to specify a path to the PEM file for the certificate
# authority for your Elasticsearch instance.
#elasticsearch.ssl.certificateAuthorities: [ "/path/to/your/CA.pem" ]
# To disregard the validity of SSL certificates, change this setting's value to 'none'.
#elasticsearch.ssl.verificationMode: full

# Time in milliseconds to wait for Elasticsearch to respond to pings. Defaults to the value of
# the elasticsearch.requestTimeout setting.
#elasticsearch.pingTimeout: 1500

# Time in milliseconds to wait for responses from the back end or Elasticsearch. This value
# must be a positive integer.
#elasticsearch.requestTimeout: 30000

# List of Kibana client-side headers to send to Elasticsearch. To send *no* client-side
# headers, set this value to [] (an empty list).
#elasticsearch.requestHeadersWhitelist: [ authorization ]

# Header names and values that are sent to Elasticsearch. Any custom headers cannot be overwritten
# by client-side headers, regardless of the elasticsearch.requestHeadersWhitelist configuration.
#elasticsearch.customHeaders: {}

# Time in milliseconds for Elasticsearch to wait for responses from shards. Set to 0 to disable.
#elasticsearch.shardTimeout: 30000
# List of Kibana client-side headers to send to Elasticsearch. To send *no* client-side
# headers, set this value to [] (an empty list).
#elasticsearch.requestHeadersWhitelist: [ authorization ]

# Header names and values that are sent to Elasticsearch. Any custom headers cannot be overwritten
# by client-side headers, regardless of the elasticsearch.requestHeadersWhitelist configuration.
#elasticsearch.customHeaders: {}

# Time in milliseconds for Elasticsearch to wait for responses from shards. Set to 0 to disable.
#elasticsearch.shardTimeout: 30000

# Logs queries sent to Elasticsearch. Requires logging.verbose set to true.
#elasticsearch.logQueries: false

# Specifies the path where Kibana creates the process ID file.
#pid.file: /run/kibana/kibana.pid

# Enables you to specify a file where Kibana stores log output.
#logging.dest: stdout

# Set the value of this setting to true to suppress all logging output.
#logging.silent: false

# Set the value of this setting to true to suppress all logging output other than error messages.
#logging.quiet: false

# Set the value of this setting to true to log all events, including system usage information
# and all requests.
#logging.verbose: false

# Set the interval in milliseconds to sample system and process performance
# metrics. Minimum is 100ms. Defaults to 5000.
#ops.interval: 5000

# Specifies locale to be used for all localizable strings, dates and number formats.
# Supported languages are the following: English - en , by default , Chinese - zh-CN .
#i18n.locale: "en"

问题处理

limit修改不生效

在 /etc/pam.d/login 中,存在:

1
session required pam_limits.so

在 /etc/pam.d/sshd 中,存在:

1
session required pam_limits.so

在 /etc/ssh/ssd_config 中, 存在:

1
2
UsePAM yes
# 修改后需要重启 systemctl restart sshd

本文地址: https://github.com/maxzhao-it/blog/post/34329/

环境

一、前言

RabbitMQ集群搭建,当前选择使用镜像模式。

技术架构:

  1. HaProxy:高可用负载
  2. KeepAlived:网络服务高可用(主从热备、秒级切换)
  3. RabiitMQ:消息队列

镜像模式,需要3台RabbitMQ服务器,一台HaProxy服务器,一台 keepAlived服务器。

二、准备

镜像模式架构图

概述

RabbitMQ 集群

RabbitMQ集群本身不是高可用的,宕机就会丢失。

RabbitMQ集群本身没有负载均衡,需要通过负载均衡实现。

RabbitMQ节点类型:

  • 内存节点:将元数据(metadata)放在内存
  • 磁盘节点:将元数据(metadata)放在磁盘(默认方式)

镜像模式中的 RabbitMQ节点类型

镜像模式中节点至少要有一个磁盘节点,用来永久持久化元数据。

为了更好的性能,可以设置多个内存节点。

磁盘节点挂掉之后,消息路由机制可以运行,一下事情不能做

  • create queues
  • create exchanges
  • create bindings
  • add users
  • change permissions
  • add or remove cluster nodes

Haproxy负载均衡

这里使用 HaProxy实现负载均衡,这里使用两台 HaProxy服务器,能够自动进行故障转移,当前解决方案为 Keepalived

Keepalived高可用

Keepalived具有高可用、主从热备、秒级切换等特点。KeepAlived 采用 VRRP (Virtual Router Redundancy Protocol,虚拟路由冗余协议)
来解决单点失效的问题,它通常由一组一备两个节点组成,同一时间内只有主节点会提供对外服务,并同时提供一个虚拟的 IP 地址 (Virtual Internet Protocol Address ,简称 VIP) 。
如果主节点故障,那么备份节点会自动接管 VIP 并成为新的主节点 ,直到原有的主节点恢复。

服务器部署方案

  • mq3:192.168.2.3 master 磁盘节点
  • mq4:192.168.2.4 slave 磁盘节点
  • mq5:192.168.2.5 slave 内存节点
  • HaProxyKeepAlived:192.168.2.6/192.168.2.7
    • 192.168.2.6 KeepAlived master
    • 192.168.2.7KeepAlived slave

三、虚拟机安装

虚拟机网络配置

虚拟机系统网络

虚拟机CD设置

四、Centos7 系统设置

1
2
sudo cp /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.bak
vim /etc/yum.repos.d/CentOS-Base.repo

详情请看附

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 清空缓存
yum clean all
# 更新源
yum repolist
# 安装基础依赖
yum -y install epel-release

sed -e 's!^metalink=!#metalink=!g' \
-e 's!^#baseurl=!baseurl=!g' \
-e 's!//download\.fedoraproject\.org/pub!//mirrors.tuna.tsinghua.edu.cn!g' \
-e 's!http://mirrors\.tuna!https://mirrors.tuna!g' \
-i /etc/yum.repos.d/epel.repo /etc/yum.repos.d/epel-testing.repo

rpm -ivh https://mirrors.tuna.tsinghua.edu.cn/epel/6/x86_64/epel-release-6-8.noarch.rpm

报错 RPM-GPG-KEY-EPEL-7

先设置 CentOS-Base.repo 中的 gpgcheck=0

1
2
cd /etc/pki/rpm-gpg
wget https://archive.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-7

国内

1
2
3
4
5
6
7
8
sudo sed -e 's|^mirrorlist=|#mirrorlist=|g' \
-e 's|^#baseurl=http://mirror.centos.org|baseurl=https://mirrors.tuna.tsinghua.edu.cn|g' \
-i.bak \
/etc/yum.repos.d/CentOS-*.repo

sudo yum clean all
sudo yum makecache
sudo yum -y update

关闭防火墙

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
systemctl status firewalld
# 关闭服务
systemctl stop firewalld
# 关闭自启服务
systemctl disable firewalld
# 开放端口
firewall-cmd --zone=public --add-port=80/tcp --add-port=3306/tcp --permanent
# 重新载入
firewall-cmd --reload
# 查看
firewall-cmd --zone=public --query-port=80/tcp
# 查看全部
firewall-cmd --zone=public --list-all
# 删除
firewall-cmd --zone=public --remove-port=80/tcp --permanent

中文字体

方式1

1
2
3
4
yum -y install fonts-chinese
yum -y install fonts-ISO8859
fc-cache -fv
reboot

方式2

1
2
3
4
yum -y install fontconfig
mkdir chinses
chmod -R 755 /usr/share/fonts/chinses/
vim /etc/fonts/fonts.conf

<dir prefix="xdg">fonts</dir> 这一行下面插入:

1
<dir>/usr/share/fonts/chinses</dir> 
1
2
# 拷贝本地字体
fc-cache

网络

需要安装 net-tools

1
yum -y install net-tools

查看网络

1
ifconfig

我这里的网络魏 ens33

编辑网络

1
vim /etc/sysconfig/network-scripts/ifcfg-ens33

1
2
3
4
5
6
7

BOOTPROTO=static #开机协议,有dhcp及static;
ONBOOT=yes #设置为开机启动;
DNS1=114.114.114.114 #这个是国内的DNS地址,是固定的;
IPADDR=192.168.2.2 #你想要设置的固定IP,理论上192.168.2.2-255之间都可以,请自行验证;
NETMASK=255.255.255.0 #子网掩码,不需要修改;
GATEWAY=192.168.2.254 #网关,这里应该和你“2.配置虚拟机的NAT模式具体地址参数”中的(2)选择VMnet8--取消勾选使用本地DHCP--设置子网IP--网关IP设置 一样才行。

重启网略

1
service network restart

测试网络

1
ping www.baidu.com

设置hostname

默认hostnamelocalhost,所以这里做区分

1
2
3
4
5
ssh root@192.168.2.3 "hostnamectl set-hostname host3;echo -e \"192.168.2.3  host3\\n192.168.2.4  host4\\n192.168.2.5  host5\\n192.168.2.6  host6\\n192.168.2.7  host7\" >> /etc/hosts;"
ssh root@192.168.2.4 "hostnamectl set-hostname host4;echo -e \"192.168.2.3 host3\\n192.168.2.4 host4\\n192.168.2.5 host5\\n192.168.2.6 host6\\n192.168.2.7 host7\" >> /etc/hosts;"
ssh root@192.168.2.5 "hostnamectl set-hostname host5;echo -e \"192.168.2.3 host3\\n192.168.2.4 host4\\n192.168.2.5 host5\\n192.168.2.6 host6\\n192.168.2.7 host7\" >> /etc/hosts;"
ssh root@192.168.2.6 "hostnamectl set-hostname host6;echo -e \"192.168.2.3 host3\\n192.168.2.4 host4\\n192.168.2.5 host5\\n192.168.2.6 host6\\n192.168.2.7 host7\" >> /etc/hosts;"
ssh root@192.168.2.7 "hostnamectl set-hostname host7;echo -e \"192.168.2.3 host3\\n192.168.2.4 host4\\n192.168.2.5 host5\\n192.168.2.6 host6\\n192.168.2.7 host7\" >> /etc/hosts;"

五、安装 RabbitMQ

Yum 安装

配置源 rabbitmq.repo

1
vim /etc/yum.repos.d/rabbitmq.repo

附录中的repo写进入就好了

1
2
3
4
5
6
# 清空缓存
yum clean all
# 更新源
yum repolist
# 更新系统
yum update -y

安装

1
2
yum install socat logrotate -y
yum install erlang rabbitmq-server -y

启动

您可以通过运行以下命令启动RabbitMQ服务器进程。

1
systemctl start rabbitmq-server

要在引导时自动启动RabbitMQ,请运行以下命令。

1
systemctl enable rabbitmq-server

要检查RabbitMQ服务器的状态,请运行:

1
systemctl status rabbitmq-server

用户管理

查看所有用户

1
sudo rabbitmqctl list_users;

添加用户

1
2
3
4
5
6
7
8
9
10
# 修改guest的密码
sudo rabbitmqctl change_password guest guest;
# 创建其他管理员账号比如test/test:
sudo rabbitmqctl add_user maxzhao maxzhao;
# 设置用户类型
sudo rabbitmqctl set_user_tags maxzhao administrator;
# /是 vhost的目录 Configure regexp Write regexp Read regexp
sudo rabbitmqctl set_permissions -p / maxzhao ".*" ".*" ".*";
# Sets user topic permissions for an exchange,默认使用 AMQP default 的exchange
# sudo rabbitmqctl set_topic_permissions

安装 Web 管理端

1
rabbitmq-plugins enable rabbitmq_management

查看系统服务

1
systemctl list-unit-files |grep rabbitmq-server

六、安装 HaProxy

1
yum install haproxy -y

这里安装后的版本为 haproxy-1.5.18

查看系统服务

1
systemctl list-unit-files |grep haproxy

这里不启动

启动

1
2
3
systemctl status haproxy
systemctl start haproxy
systemctl enable haproxy

七、安装 KeepAlived

下载

官方下载地址

这里选择 2.2.2版本

1
2
3
mkdir /root/tools
cd /root/tools/
wget https://www.keepalived.org/software/keepalived-2.2.2.tar.gz

安装

VMware 中注意,需要挂载ISO镜像,参考 VMWare配置CentOS7网络

1
2
3
4
5
6
yum -y install openssl-devel gcc gcc-c++
tar -xvf keepalived-2.2.2.tar.gz
cd keepalived-2.2.2
./configure --prefix=/usr/local/keepalived
make && make install
mkdir /etc/keepalived

安装后的目录

1
2
yum install tree -y
tree -l /usr/local/keepalived/etc

输出

1
2
3
4
5
6
7
8
9
10
11
/usr/local/keepalived/etc
├── keepalived
│   ├── keepalived.conf
│   └── samples
│   ├── client.pem
│   ├── dh1024.pem
│   ├── keepalived.conf.conditional_conf
│   ├── ***********************************
│   └── sample_notify_fifo.sh
└── sysconfig
└── keepalived

分别对应

1
2
/etc/keepalived/keepalived.conf
/etc/sysconfig/keepalived

创建启动文件

1
2
3
4
5
6
#将keepalived配置文件拷贝到etc下
cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/keepalived.conf
#将keepalived文件拷贝到etc下,加入网卡配置
cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/keepalived
#命令
ln -s /usr/local/keepalived/sbin/keepalived /usr/sbin

查看系统服务

1
systemctl list-unit-files |grep keepalived

这里先不启动

八、拷贝虚拟机

我这里用的虚拟机,如果使用 Docker,直接启动 Docker 容器就可以了。

虚拟机

VMware 操作步骤

  1. 虚拟机关机
  2. 拷贝出5台设备
  3. 修改5台设备网络
    • 192.168.2.3
      • RabbitMQ master
    • 192.168.2.4
      • RabbitMQ
    • 192.168.2.5
      • RabbitMQ
    • 192.168.2.6
      • HaProxy
      • KeepAlived master
    • 192.168.2.7
      • HaProxy
      • KeepAlived slave

开放虚拟机端口或关闭防火墙

开放端口

1
2
3
4
5
ssh root@192.168.2.3  "firewall-cmd --zone=public --add-port=80/tcp --add-port=3306/tcp --add-port=5672/tcp --add-port=15672/tcp --permanent;firewall-cmd --zone=public --list-all"
ssh root@192.168.2.4 "firewall-cmd --zone=public --add-port=80/tcp --add-port=3306/tcp --add-port=5672/tcp --add-port=15672/tcp --permanent;firewall-cmd --zone=public --list-all"
ssh root@192.168.2.5 "firewall-cmd --zone=public --add-port=80/tcp --add-port=3306/tcp --add-port=5672/tcp --add-port=15672/tcp --permanent;firewall-cmd --zone=public --list-all"
ssh root@192.168.2.6 "firewall-cmd --zone=public --add-port=80/tcp --add-port=3306/tcp --add-port=5672/tcp --add-port=15672/tcp --permanent;firewall-cmd --zone=public --list-all"
ssh root@192.168.2.7 "firewall-cmd --zone=public --add-port=80/tcp --add-port=3306/tcp --add-port=5672/tcp --add-port=15672/tcp --permanent;firewall-cmd --zone=public --list-all"

关闭防火墙

1
2
3
4
5
ssh root@192.168.2.3  "systemctl stop firewalld;systemctl disable firewalld;"
ssh root@192.168.2.4 "systemctl stop firewalld;systemctl disable firewalld;"
ssh root@192.168.2.5 "systemctl stop firewalld;systemctl disable firewalld;"
ssh root@192.168.2.6 "systemctl stop firewalld;systemctl disable firewalld;"
ssh root@192.168.2.7 "systemctl stop firewalld;systemctl disable firewalld;"

配置

一、配置 RabbitMQ

配置文件

1
2
# 查找配置文件
rabbitmq-diagnostics status

找到 Config files 部分

1
2
3
4
Config files

* /etc/rabbitmq/advanced.config
* /etc/rabbitmq/rabbitmq.conf

修改配置文件

1
vim /etc/rabbitmq/rabbitmq.conf

配置

1
2
3
4
5
# 端口
#listeners.tcp.default = 5672
listeners.tcp.1 = 192.168.2.3:5672
# 配置远程登录的账号
loopback_users.maxzhao = false

重启

1
2
systemctl restart rabbitmq-server
systemctl status rabbitmq-server

普通集群

$HOME/var/lib/rabbitmq中有一个 .erlang.cookie 文件。

1
2
ls -la $HOME|grep .erlang.cookie
ls -la /var/lib/rabbitmq|grep .erlang.cookie

RabbitMQ 集群是依赖 erlang集群的,erlang集群需要 cookie 通讯认证,必须要同一个 cookie 才可以通讯。

192.168.2.3服务器上执行

1
2
3
4
5
6
7
8
# 第二台服务器
ssh root@192.168.2.4 "systemctl stop rabbitmq-server"
scp /var/lib/rabbitmq/.erlang.cookie root@192.168.2.4:/var/lib/rabbitmq/
ssh root@192.168.2.4 "chmod 600 /var/lib/rabbitmq/.erlang.cookie ;systemctl start rabbitmq-server"
# 第三台服务器
ssh root@192.168.2.5 "systemctl stop rabbitmq-server"
scp /var/lib/rabbitmq/.erlang.cookie root@192.168.2.5:/var/lib/rabbitmq/
ssh root@192.168.2.5 "chmod 600 /var/lib/rabbitmq/.erlang.cookie ;systemctl start rabbitmq-server"

查看集群节点状态

192.168.2.3服务器上执行

1
rabbitmqctl status

这里会发现

1
Starting node rabbit@localhost ...

这里需要设置服务器名称之后就没有当前问题

1
2
3
4
5
6
7
ssh root@192.168.2.3 "hostnamectl set-hostname host3;systemctl restart rabbitmq-server;rabbitmqctl status|head"
ssh root@192.168.2.4 "hostnamectl set-hostname host4;systemctl restart rabbitmq-server;rabbitmqctl status|head"
ssh root@192.168.2.5 "hostnamectl set-hostname host5;systemctl restart rabbitmq-server;rabbitmqctl status|head"
# 设置各个节点地址
ssh root@192.168.2.3 "echo -e \"192.168.2.3 host3\\n192.168.2.4 host4\\n192.168.2.5 host5\\n192.168.2.6 host6\\n192.168.2.7 host7\" >> /etc/hosts;"
ssh root@192.168.2.4 "echo -e \"192.168.2.3 host3\\n192.168.2.4 host4\\n192.168.2.5 host5\\n192.168.2.6 host6\\n192.168.2.7 host7\" >> /etc/hosts;"
ssh root@192.168.2.5 "echo -e \"192.168.2.3 host3\\n192.168.2.4 host4\\n192.168.2.5 host5\\n192.168.2.6 host6\\n192.168.2.7 host7\" >> /etc/hosts;"

查看集群状态

192.168.2.3服务器上执行

1
rabbitmqctl cluster_status

结果只有当前一个节点

添加集群节点

192.168.2.3上执行当前操作

join_cluster参数

  • –disc new node should be a disk one default
  • – ram new node should be a RAM one
1
2
3
4
5
6
# host4加入集群
ssh root@192.168.2.4 "rabbitmqctl stop_app;rabbitmqctl join_cluster --ram rabbit@host3;rabbitmqctl start_app;systemctl restart rabbitmq-server;"
# host5加入集群
ssh root@192.168.2.4 "rabbitmqctl stop_app;rabbitmqctl join_cluster --ram rabbit@host3;rabbitmqctl start_app;systemctl restart rabbitmq-server;"
# 查看集群状态
rabbitmqctl cluster_status

打开 web

镜像集群

策略policy

镜像集群依赖于 policy 模块.

策略用于设置Exchanges或者queue的数据复制、同步。

1
rabbitmqctl set_policy ha-all "^" '{"ha-mode":"all"}'
  • ha-all:策略名称。
  • ^:为匹配符,只有一个代表匹配所有,^qfedu为匹配名称为qfeduexchanges或者queue
  • ha-mode:为匹配类型,他分为3种模式:
    • all:所有(所有的 queue),
    • exctly:部分(需配置ha-params参数,此参数为int类型, 比如3,众多集群中的随机3台机器),
    • nodes:指定(需配置ha-params参数,此参数为数组类型比如[“rabbit@F”,“rabbit@G”]这样指定为F与G这2台机器。)

节点下线

1
2
3
4
5
6
# 下线的服务器执行,比如 host5
rabbitmqctl stop
# 任意集群中的节点服务器执行,比如 host4
rabbitmqctl forget_cluster_node rabbit@host5
# 或者 host5 上执行,这会清空该节点上所有历史数据,并主动通知集群中其它节点它将要离开集群。
rabbitmqctl reset

集群关闭与重启

没有一个直接的命令可以关闭整个集群,需要逐一进行关闭。

但是在重启时,最后关闭的节点最先被启动。如果第一个启动的不是最后关闭的节点,那么这个节点会等待最后关闭的那个节点启动,默认进行 10 次连接尝试,超时时间为 30 秒,如果依然没有等到,则该节点启动失败。

这带来的一个问题是,假设在一个三节点的集群当中,关闭的顺序为 host3host4host5,如果 host3 因为故障暂时没法恢复,此时 host4host5
就无法启动。想要解决这个问题,可以先将 host3 节点进行剔除,命令如下:

1
rabbitmqctl forget_cluster_node rabbit@host3 -offline

-offline 参数:允许节点在自身没有启动的情况下将其他节点剔除。

二、配置 HaProxy

配置

基本配置haproxy.cfg

参考附录 /etc/haproxy/haproxy.cfg

1
vim /etc/haproxy/haproxy.cfg

日志配置 rsyslog

1
2
3
4
5
mkdir /var/log/haproxy
vim /etc/rsyslog.conf
#写入 local2.* /var/log/haproxy.log
systemctl restart rsyslog.service
systemctl restart haproxy

检查配置

1
2
haproxy -f /etc/haproxy/haproxy.cfg -c
#Configuration file is valid

启动

1
2
systemctl start haproxy
systemctl enable haproxy

测试访问

问题 rabbitmq_cluster: cannot bind socket [0.0.0.0:5672]

设置策略

1
2
3
4
5
6
# 方式一
setsebool -P haproxy_connect_any=1
# 方式二
vim /etc/sysctl.conf
# 添加 net.ipv4.ip_nonlocal_bind=1
sysctl -p

重新启动就可以了.

三、配置KeepAlived

Keepalived 启动时,不会检查配置文件的语法。

配置文件修改

1
vim /etc/keepalived/keepalived.conf

master 192.168.2.6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
global_defs { ## 全局定义块 
router_id host6 ## 标识本节点的字条串,通常为hostname
}
vrrp_script check_haproxy {
script "/etc/keepalived/haproxy_chk.sh" #执行脚本位置
interval 5 ##检查时间间隔
weight -20 ##如果条件成立则权重减20
}
vrrp_instance VI_1 { #VRRP 实例定义块
state MASTER ##主节点为MASTER,备份节点为BACKUP
interface ens33 ##绑定虚拟ip的网络接口(网卡)
virtual_router_id 80 ##虚拟路由id号,主备节点相同
mcast_src_ip 192.168.2.6 ##本机ip地址
priority 100 ##优先级(0-254)
advert_int 1 ##组播信息发送间隔,两个节点必须一致,默认1s
authentication { ##认证匹配
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.2.8/24 ##虚拟ip,可以指定多个
}
track_script {
check_haproxy
}
}

slave 192.168.2.7

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
global_defs { ## 全局定义块 
router_id host7 ## 标识本节点的字条串,通常为hostname
}
vrrp_script check_haproxy {
script "/etc/keepalived/haproxy_chk.sh" #执行脚本位置
interval 5 ##检查时间间隔
weight -20 ##如果条件成立则权重减20
}
vrrp_instance VI_1 { #VRRP 实例定义块
state MASTER ##主节点为MASTER,备份节点为BACKUP
interface ens33 ##绑定虚拟ip的网络接口(网卡)
virtual_router_id 80 ##虚拟路由id号,主备节点相同
mcast_src_ip 192.168.2.7 ##本机ip地址
priority 50 ##优先级(0-254)
advert_int 1 ##组播信息发送间隔,两个节点必须一致,默认1s
authentication { ##认证匹配
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.2.8/24 ##虚拟ip,可以指定多个
}
track_script {
check_haproxy
}
}

日志配置

1
2
3
4
5
6
vim /etc/sysconfig/keepalived
#写入 KEEPALIVED_OPTIONS="-D -d -S 0"
vim /etc/rsyslog.conf
#写入 local0.* /var/log/keepalived.log
systemctl restart rsyslog.service
systemctl restart keepalived

健康检查脚本

1
vim /etc/keepalived/haproxy_chk.sh
1
2
3
4
5
6
7
8
9
systemctl status haproxy.service &>/dev/null
if [ $? -ne 0 ];then
systemctl start haproxy.service &>/dev/null
sleep 5
systemctl status haproxy.service &>/dev/null
if [ $? -ne 0 ];then
systemctl stop keepalived
fi
fi
1
chmod 755 /etc/keepalived/haproxy_chk.sh

启动

1
2
3
4
useradd  keepalived_script
systemctl start keepalived
systemctl enable keepalived
systemctl status keepalived

测试

查看进程

keepalived正常运行后,会启动2个进程,其中一个是父进程,负责监控其子进程。一个是vrrp子进程。

1
2
root       2607      1  0 15:35 ?        00:00:00 /usr/local/keepalived/sbin/keepalived -D
root 2608 2607 0 15:35 ? 00:00:00 /usr/local/keepalived/sbin/keepalived -D

IP

1
2
# 在 `host6` 上执行
ip a

host7 上执行,是没有当前 VIP 的。

1
2
3
4
# 在 `host6` 上执行
systemctl stop keepalived
# 在 `host7` 上执行
ip a

这时候会发现 VIP 节点就到了 host7

1
2
3
4
# 在 `host6` 上执行
systemctl start keepalived
# 在 `host6` 上执行
ip a

会发现 VIP 节点又回来了,因为 host6priorityhost7大,所以会抢夺。

禁用抢夺策略:

1
2
3
4
vrrp_instance VI_1 {
##**************
nopreempt
}

正常测试

1
2
3
4
5
6
7
curl 192.168.2.6
#this is master
#root@centos7[14:46:07]:~
curl 192.168.2.7
#this is master
#root@centos7[15:03:29]:~
#1.2.3.4.5.6.

关闭 master 后测试

1
systemctl stop keepalived
1
2
3
curl 192.168.2.7
#this is slave
#root@centos7[15:03:59]:/etc/keepalived

推荐文档

RabbitMQ 官方文档 —— 集群指南
RabbitMQ 官方文档 —— 高可用镜像队列
HAProxy 官方配置手册
KeepAlived 官方配置手册

清华大学 repo 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# CentOS-Base.repo
#
# The mirror system uses the connecting IP address of the client and the
# update status of each mirror to pick mirrors that are updated to and
# geographically close to the client. You should use this for CentOS updates
# unless you are manually picking other mirrors.
#
# If the mirrorlist= does not work for you, as a fall back you can try the
# remarked out baseurl= line instead.
#
#


[base]
name=CentOS-$releasever - Base
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/os/$basearch/
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-7

#released updates
[updates]
name=CentOS-$releasever - Updates
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/updates/$basearch/
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-7



#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/extras/$basearch/
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-7



#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus
baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/centosplus/$basearch/
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-7

rabbitmq.conf

/etc/rabbitmq/rabbitmq.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 端口
#listeners.tcp.default = 5672
listeners.tcp.1 = 192.168.2.3:5672
# 接受 TCP 侦听器连接的 Erlang 进程的数目
num_acceptors.tcp = 10
# 握手的最大时间(在套接字连接和 TLS 握手之后) ,以毫秒为单位
handshake_timeout = 10000
#listeners.ssl
# 接受客户端 TLS 连接的 Erlang 进程数量
num_acceptors.ssl = 10
# TLS 配置 TLS guide 指南. https://www.rabbitmq.com/ssl.html#enabling-ssl
ssl_options = none
#TLS 握手超时,以毫秒为单位
ssl_handshake_timeout = 5000
# 触发流控制的内存阈值。可以是操作系统可用 RAM 的绝对值或相对值:
vm_memory_high_watermark.relative = 0.6
#vm_memory_high_watermark.absolute = 2GB
#内存使用报告策略。可以是下列策略之一:
#allocated : 使用 Erlang 内存分配器统计信息
#rss : 使用操作系统 RSS 内存报告。这使用特定于操作系统的方法,并可能启动短命的子进程
#legacy : 使用遗留内存报告(认为运行时使用了多少内存)。这种策略是相当不准确的
#erlang : 与legacy 相似, 保存为向后兼容
vm_memory_calculation_strategy = allocated
#与客户端协商的最大允许信道数,不包括协议中使用的特殊信道0。设置为0意味着“无限”,这是一个危险的值,因为应用程序有时会有通道泄漏。使用更多的通道会增加代理的内存占用
channel_max = 2047
#道操作超时(以毫秒为单位)(在内部使用,由于消息传递协议的差异和限制,不会直接暴露给客户端)
channel_operation_timeout = 15000
#表示服务器在连接参数协商期间建议的心跳超时。如果两端设置为0,则禁用心跳(不建议这样做)
heartbeat = 60
default_user = guest
default_pass = guest
default_user_tags.administrator = true
#在创建默认用户时赋值给默认用户
default_permissions.configure = .*
default_permissions.read = .*
default_permissions.write = .*
# 配置远程登录的账号
loopback_users.maxzhao = false
#后端要联系的节点列表。例如,在第一次启动时使用节点‘ rabbit@hostname1’和‘ rabbit@hostname2’进行集群:
#cluster_formation.classic_config.nodes.1 = rabbit@hostname1
#cluster_formation.classic_config.nodes.2 = rabbit@hostname2
#集群名称 每个都不一样
cluster_name = rabbit@192.168.2.3

RabbitMQ-repo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
##
## Zero dependency Erlang
##
[rabbitmq_erlang]
name=rabbitmq_erlang
baseurl=https://packagecloud.io/rabbitmq/erlang/el/7/$basearch
repo_gpgcheck=1
gpgcheck=1
enabled=1
# PackageCloud's repository key and RabbitMQ package signing key
gpgkey=https://packagecloud.io/rabbitmq/erlang/gpgkey
https://github.com/rabbitmq/signing-keys/releases/download/2.0/rabbitmq-release-signing-key.asc
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt
metadata_expire=300

[rabbitmq_erlang-source]
name=rabbitmq_erlang-source
baseurl=https://packagecloud.io/rabbitmq/erlang/el/7/SRPMS
repo_gpgcheck=1
gpgcheck=0
enabled=1
gpgkey=https://packagecloud.io/rabbitmq/erlang/gpgkey
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt
metadata_expire=300
##
## RabbitMQ server
##
[rabbitmq_server]
name=rabbitmq_server
baseurl=https://packagecloud.io/rabbitmq/rabbitmq-server/el/7/$basearch
repo_gpgcheck=1
gpgcheck=1
enabled=1
# PackageCloud's repository key and RabbitMQ package signing key
gpgkey=https://packagecloud.io/rabbitmq/rabbitmq-server/gpgkey
https://github.com/rabbitmq/signing-keys/releases/download/2.0/rabbitmq-release-signing-key.asc
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt
metadata_expire=300

[rabbitmq_server-source]
name=rabbitmq_server-source
baseurl=https://packagecloud.io/rabbitmq/rabbitmq-server/el/7/SRPMS
repo_gpgcheck=1
gpgcheck=0
enabled=1
gpgkey=https://packagecloud.io/rabbitmq/rabbitmq-server/gpgkey
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt
metadata_expire=300

haproxy

/etc/haproxy/haproxy.cfg

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#全局配置
global
#设置日志 local为本地
log 127.0.0.1 local2 info
#当前工作目录
chroot /var/lib/haproxy
#pid 文件地址
pidfile /var/run/haproxy.pid
#用户与用户组
user haproxy
group haproxy
#运行进程ID
#uid 99
#gid 99
#守护进程启动
daemon
#最大连接数
maxconn 4096
# turn on stats unix socket
stats socket /var/lib/haproxy/stats
#默认配置
defaults
#应用全局的日志配置
log global
#默认的模式mode {tcp|http|health}
#TCP是4层,HTTP是7层,health只返回OK
mode http
#日志类别tcplog/httplog
option httplog
#不记录健康检查日志信息
option dontlognull
#3次失败则认为服务不可用
retries 3
#每个进程可用的最大连接数
maxconn 2000
#连接超时
timeout connect 5s
#客户端超时
timeout client 120s
#服务端超时
timeout server 120s

# RabbitMQ 集群绑定配置
listen rabbitmq_cluster
bind *:5672
option tcplog
#配置TCP模式
mode tcp
#轮询算法
balance roundrobin
#RabbitMQ集群节点配置
server rabbitmq1 192.168.2.3:5672 check inter 5000 rise 2 fall 3 weight 1
server rabbitmq2 192.168.2.4:5672 check inter 5000 rise 2 fall 3 weight 1
server rabbitmq3 192.168.2.5:5672 check inter 5000 rise 2 fall 3 weight 1

#haproxy监控页面地址
listen monitor
bind *:8100
mode http
option httplog
stats enable
stats uri /stats
stats refresh 5s

Keepalived

/etc/keepalived/keepalived.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#全局定义块
global_defs {
## 标识本节点的字条串,通常为hostname
router_id host6
}
vrrp_script check_haproxy {
#执行脚本位置
script "/etc/keepalived/haproxy_chk.sh"
##检查时间间隔
interval 5
##如果条件成立则权重减20
weight -20
}
#VRRP 实例定义块
vrrp_instance VI_1 {
##主节点为MASTER,备份节点为BACKUP
state MASTER
##绑定虚拟ip的网络接口(网卡)
interface ens33
##虚拟路由id号,主备节点相同
virtual_router_id 80
##本机ip地址
mcast_src_ip 192.168.2.6
##优先级(0-254),
priority 100
##组播信息发送间隔,两个节点必须一致,默认1s
advert_int 1
##认证匹配
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
##虚拟ip,可以指定多个
192.168.2.8/24
}
track_script {
check_haproxy
}
}

VRRP实例定义块

  1. vrrp_sync_group:同步vrrp级,用于确定失败切换(FailOver)包含的路由实例个数。即在有2个负载均衡器的场景,一旦某个负载均衡器失效,需要自动切换到另外一个负载均衡器的实例是哪
  2. group:至少要包含一个vrrp实例,vrrp实例名称必须和vrrp_instance定义的一致
  3. vrrp_instance:vrrp实例名 1> state:实例状态,只有MASTER 和
    BACKUP两种状态,并且需要全部大写。抢占模式下,其中MASTER为工作状态,BACKUP为备用状态。当MASTER所在的服务器失效时,BACKUP所在的服务会自动把它的状态由BACKUP切换到MASTER状态。当失效的MASTER所在的服务恢复时,BACKUP从MASTER恢复到BACKUP状态。
    2> interface:对外提供服务的网卡接口,即VIP绑定的网卡接口。如:eth0,eth1。当前主流的服务器都有2个或2个以上的接口(分别对应外网和内网),在选择网卡接口时,一定要核实清楚。 3> **
    mcast_src_ip:本机IP地址 4> virtual_router_id:虚拟路由的ID号,每个节点设置必须一样,可选择IP最后一段使用,相同的 VRID 为一个组,他将决定多播的 MAC 地址。 5> **
    priority
    :节点优先级,取值范围0~254,MASTER要比BACKUP高 6> advert_int:MASTER与BACKUP节点间同步检查的时间间隔,单位为秒 7> **
    lvs_sync_daemon_inteface:负载均衡器之间的监控接口,类似于 HA HeartBeat 的心跳线。但它的机制优于 Heartbeat,因为它没有“裂脑”这个问题,它是以优先级这个机制来规避这个麻烦的。在 DR
    模式中,lvs_sync_daemon_inteface与服务接口interface使用同一个网络接口 8> authentication:验证类型和验证密码。类型主要有 PASS、AH
    两种,通常使用PASS类型,据说AH使用时有问题。验证密码为明文,同一vrrp 实例MASTER与BACKUP使用相同的密码才能正常通信。 9> smtp_alert:有故障时是否激活邮件通知 10> **
    nopreempt

    :禁止抢占服务。默认情况,当MASTER服务挂掉之后,BACKUP自动升级为MASTER并接替它的任务,当MASTER服务恢复后,升级为MASTER的BACKUP服务又自动降为BACKUP,把工作权交给原MASTER。当配置了nopreempt,MASTER从挂掉到恢复,不再将服务抢占过来。
    11> virtual_ipaddress:虚拟IP地址池,可以有多个IP,每个IP占一行,不需要指定子网掩码。注意:这个IP必须与我们的设定的vip保持一致。

虚拟服务器virtual_server定义块

    1. virtual_server:定义一个虚拟服务器,这个ip是virtual_ipaddress中定义的其中一个,后面一个空格,然后加上虚拟服务的端口号。 1> delay_loop:健康检查时间间隔,单位:秒 2>
      lb_algo:负载均衡调度算法,互联网应用常用方式为wlc或rr 3> lb_kind:负载均衡转发规则。包括DR、NAT、TUN 3种,一般使用路由(DR)转发规则。 4>
      persistence_timeout:http服务会话保持时间,单位:秒 5> protocol:转发协议,分为TCP和UDP两种
    2. real_server:真实服务器IP和端口,可以定义多个 1> weight:负载权重,值越大,转发的优先级越高 2> notify_down:服务停止后执行的脚本 3> TCP_CHECK:服务有效性检测 *
      connect_port:服务连接端口 * connect_timeout:服务连接超时时长,单位:秒 * nb_get_retry:服务连接失败重试次数 * delay_before_retry:重试连接间隔,单位:秒

配置日志文件

RabbitMQ 集群常用命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
五、集群常用命令
1、加入集群[--ram添加内存模式 默认disk模式]
rabbitmqctl join_cluster --ram rabbit@mq01

2、查看集群状态
rabbitmqctl cluster_status

3、更改节点模式[顺序 关闭运用-〉更改类型->开启运用]
rabbitmqctl stop_app –停止运用服务
rabbitmqctl change_cluster_node_type disc/ram –更改节点为磁盘或内存节点
rabbitmqctl start_app –开启运用服务

4、创建策略(集群同步策略……)
set_policy [-p vhostpath] {name} {pattern} {definition} [priority]

5、查看策略
rabbitmqctl list_policies

6、移除远程offline的节点
1.节点2停掉应用
rabbitmqctl stop_app
2.节点1执行删除
rabbitmqctl forget_cluster_node rabbit@host5

7、设置集群名称
rabbitmqctl set_cluster_name cluster_name

8、设置镜像模式
Rabbit提供镜像功能,需要基于rabbitmq策略来实现,政策是用来控制和修改群集范围的某个vhost队列行为和Exchange行为
set_policy [-p vhostpath] {name} {pattern} {definition} [priority]
rabbitmqctl set_policy ha-all "^ha." "{""ha-mode"":""all""}"
rabbitmqctl set_policy ha-all "^" "{""ha-mode"":""all"",""ha-sync-mode"":""automatic""}"
rabbitmqctl set_policy -p demo ha-all "^" "{""ha-mode"":""all"",""ha-sync-mode"":""automatic""}"

9、手动同步queue
rabbitmqctl sync_queue name

10、取消queue同步
rabbitmqctl cancel_sync_queue name

11、查看所有队列信息
rabbitmqctl list_queues

12、获取队列信息
rabbitmqctl list_queues[-p vhostpath] [queueinfoitem ...]
Queueinfoitem可以为:name,durable,auto_delete,arguments,messages_ready,messages_unacknowledged,messages,consumers,memory。

13、获取Exchange信息
rabbitmqctl list_exchanges[-p vhostpath] [exchangeinfoitem ...]
Exchangeinfoitem有:name,type,durable,auto_delete,internal,arguments。

14、获取Binding信息
rabbitmqctl list_bindings[-p vhostpath] [bindinginfoitem ...]
Bindinginfoitem有:source_name,source_kind,destination_name,destination_kind,routing_key,arguments。

15、获取Connection信息
rabbitmqctl list_connections [connectioninfoitem ...]
Connectioninfoitem有:recv_oct,recv_cnt,send_oct,send_cnt,send_pend等。

16、获取Channel信息
rabbitmqctl list_channels[channelinfoitem ...]
Channelinfoitem有consumer_count,messages_unacknowledged,messages_uncommitted,acks_uncommitted,messages_unconfirmed,prefetch_count,client_flow_blocked。

本文地址: https://github.com/maxzhao-it/blog/post/33972/

先在虚拟机中挂载光驱

1
2
3
4
5
6
7
lsblk ##查看光盘是否连接上
# sr0 11:0 1 8.8G 0 rom /mnt/cdrom
mkdir /mnt/cdrom/ ##创建挂载点
mount /dev/cdrom /mnt/cdrom/ ##挂载光盘
cp /etc/yum.repos.d/ -r /root/
# rm -rf /etc/yum.repos.d/* ##删除原有仓库文件
vi /etc/yum.repos.d/localrepo.repo ##编辑仓库配置文件

i 进入编辑模式

1
2
3
4
5
[CentOS7]									##仓库标识
name='CentOS - localrepo' ##仓库名称
baseurl=file:///mnt/cdrom ##仓库路径
enabled=1 ##是否启用
gpgcheck=0 ##是否检验签名

保存并退出:按一下 esc 输入 :wq

1
2
3
4
5
yum clean all							##清理缓存
yum repolist ##生成新的缓存
##安装相关软件,提供常用命令以及tab键功能,安装完成需要重启
yum -y install net-tools vim bash-computletion psmisc
reboot ##重启

重启后光盘需要重新挂载,永久挂载需写入配置文件,如下

1
vim /etc/fstab 

写入

1
/dev/cdrom /mnt/cdrom iso9660	defaults 0 0

检查挂载是否正确

1
mount -a

结果

1
mount: /dev/sr0 #写保护,将以只读方式挂载

本文地址: https://github.com/maxzhao-it/blog/post/47398/

需要安装 net-tools

查看网络

1
ifconfig

我这里的网络为 ens33

编辑网络

1
vim ifcfg-ens33

1
2
3
4
5
6
7

BOOTPROTO=static #开机协议,有dhcp及static;
ONBOOT=yes #设置为开机启动;
DNS1=114.114.114.114 #这个是国内的DNS地址,是固定的;
IPADDR=192.168.2.2 #你想要设置的固定IP,理论上192.168.2.2-255之间都可以,请自行验证;
NETMASK=255.255.255.0 #子网掩码,不需要修改;
GATEWAY=192.168.2.254 #网关,这里应该和你“2.配置虚拟机的NAT模式具体地址参数”中的(2)选择VMnet8--取消勾选使用本地DHCP--设置子网IP--网关IP设置 一样才行。

重启网略

1
service network restart

测试网络

1
ping www.baidu.com

本文地址: https://github.com/maxzhao-it/blog/post/9815/

前言

Docker 中,volumes 相比 mounts

  1. 更容易备份或者迁移
  2. Docker Cli 或者 Docker Api 管理 Volumes
  3. 跨平台的
  4. 安全的容器之间共享 Volumes
  5. Volumes驱动 可以远程存储或云提供,可以加密,可以添加其他功能
  6. 新的 Volumes 可以通过容器预先填充内容
  7. VolumesMacWindows主机上,有更高的性能。

命令操作

Volumes操作

创建

1
docker volume create redis-vol

查看

1
docker volume ls

Inspect

1
docker volume inspect redis-vol

检查结果

1
2
3
4
5
6
7
8
9
10
11
[
{
"CreatedAt": "2021-08-02T07:33:01Z",
"Driver": "local",
"Labels": {},
"Mountpoint": "/var/lib/docker/volumes/redis-vol/_data",
"Name": "redis-vol",
"Options": {},
"Scope": "local"
}
]

删除

1
docker volume rm redis-vol

挂载

下面两种方式结果相同,但只能同时运行一个,除非删除 some-redisredis-vol

-v方式挂载

1
docker run --name some-redis -v redis-vol:/data -p 6379:6379 -d redis redis-server --appendonly yes  

--mount方式挂载

1
docker run --name some-redis --mount source=redis-vol,target=/data   -p 6379:6379 -d redis redis-server --appendonly yes  

检查是够挂载

1
docker inspect some-redis

删除容器删除Volumes

1
2
3
docker container stop some-redis
docker container rm some-redis
docker volume rm redis-vol

配置docker-compose.yml

包含 Volumesyml

1
2
3
4
5
6
7
8
9
10
version: "3.9"
services:
redis1:
image: redis:latest
volumes:
- redis2-vol:/data
ports:
- "6379:6379"
volumes:
redis2-vol:

使用 Volumesyml

创建 volumes

1
docker volume create redis3-vol

使用 volumes

1
2
3
4
5
6
7
8
9
10
11
version: "3.9"
services:
redis1:
image: redis:latest
volumes:
- redis3-vol:/data
ports:
- "6379:6379"
volumes:
redis3-vol:
external: true

更多参考 docks.docker

本文地址: https://github.com/maxzhao-it/blog/post/12280/

前言

数据量小,容灾使用 主备模式 很方便。

一般使用 镜像模式。

远程模式太老套,也会出现脏数据,多活模式也会出现脏数据。

四种模式

1、主备模式

使用主节点,主节点宕机用备份节点,主节点上线后,继续使用主节点。数据不同步,不常用。

2、远程模式

比较早期的 shovel 模式,可以实现双活

3、镜像模式

mirror 镜像模式,保证 100% 数据不丢失。在实际工作中也是用得最多的,并且实现非常的简单,一般互联网大厂都会构建这种镜像集群模式。

目的是高可用,一般需要2-3个节点。100% 数据可靠性解决方案,一般采用3个节点。

4、多活模式

实现异地集群的都是采用这种双活 或者 多活模型来实现。

本文地址: https://github.com/maxzhao-it/blog/post/934/