如何正确的关闭ElasticSearch集群

背景
接触Elasticsearch也快半年时间了,一直也没弄明白如何的关闭ES和ES集群。经常在测试和生产环境遇到这样的问题“重启ES后数据怎么没了?”,“启动ES后,怎么一直有大量的数据在迁移?”

问题原因

其本质原因有两点:

ES中的数据不是实时写入磁盘的。数据进入ES后先进入data buffer和log buffer,然后进入数据段,最后再特定时机下才刷入磁盘。即在内存中有很多数据是没写入磁盘的。

ES的自动分片机制。当集群发现经过一分钟后(index.unassigned.node_left.delayed_timeout参数设置)还连接不上某个节点,就会把集群内的数据重新进行分布,即使后来节点重新连接上,原来的数据因为重新分布也无效了。

如何正确的关闭ES或者ES集群

  • 第一步,禁止分片自动分布
    1. PUT _cluster/settings
    2. {
    3. "persistent": {
    4. "cluster.routing.allocation.enable": "none"
    5. }
    6. }
  • 第二步,执行同步刷新
    1. POST _flush/synced
  • 第三步,各节点逐个关闭
    1. # 通过服务关闭
    2. # sudo systemctl stop elasticsearch.service
    3. # 杀进程关闭
    4. kill $(cat pid.txt)

如何启动ES集群

  • 第一步,执行完操作后逐个启动节点

    1. cd $ES_HOME/bin
    2. ./elasticsearch -d -p $ES_HOME/pid.txt
  • 第二步,等待所有节点加入集群

    1. GET _cat/health
    2. GET _cat/nodes
  • 第三步,启用分片自动分布

    1. PUT _cluster/settings
    2. {
    3. "persistent": {
    4. "cluster.routing.allocation.enable": null
    5. }
    6. }
  • 第四步,等待集群可用
    通过集群的状态和恢复进程监控集群是否可用

    1. GET _cat/health
    2. GET _cat/recovery

关闭脚本

  1. #! /bin/bash
  2. esurl=$1
  3. curl -XPUT -H "Content-Type: application/json" -d "{\"persistent\":{\"cluster.routing.allocation.enable\":\"none\"}}" http://$1/_cluster/settings
  4. sleep 0.5
  5. curl -XPOST http://$1/_flush/synced

启动检查脚本

  1. #! /bin/bash
  2. curl http://$1/_cat/health
  3. curl http://$1/_cat/nodes
  4. curl http://$1/_cat/recovery

启动分片自动分布

  1. curl -XPUT -H "Content-Type: application/json" -d "{\"persistent\":{\"cluster.routing.allocation.enable\":null}}" http://$1/_cluster/settings
文档更新时间: 2020-12-28 11:33   作者:张尚