Elasticsearch 6.1.0线程池介绍

简介: 开篇  这篇文章主要是用来讲解ES线程池(EsExecutors)的实现,然后象征性的和JDK的Executors实现进行了简单的对比,看了这篇文章以后要对Executors和ThreadPoolExecutor的使用更有信心才对。

开篇

 这篇文章主要是用来讲解ES线程池(EsExecutors)的实现,然后象征性的和JDK的Executors实现进行了简单的对比,看了这篇文章以后要对Executors和ThreadPoolExecutor的使用更有信心才对。


elasticsearch线程池配置

public class ThreadPool extends AbstractComponent implements Scheduler, Closeable {

  final int availableProcessors = EsExecutors.numberOfProcessors(settings);
  final int halfProcMaxAt5 = halfNumberOfProcessorsMaxFive(availableProcessors);
  final int halfProcMaxAt10 = halfNumberOfProcessorsMaxTen(availableProcessors);
  final int genericThreadPoolMax = boundedBy(4 * availableProcessors, 128, 512);

  builders.put(Names.GENERIC, 
  new ScalingExecutorBuilder(Names.GENERIC, 4, genericThreadPoolMax, TimeValue.timeValueSeconds(30)));

  builders.put(Names.INDEX, 
  new FixedExecutorBuilder(settings, Names.INDEX, availableProcessors, 200));

  builders.put(Names.BULK, 
  new FixedExecutorBuilder(settings, Names.BULK, availableProcessors, 200)); 

  builders.put(Names.GET, 
  new FixedExecutorBuilder(settings, Names.GET, availableProcessors, 1000));

  builders.put(Names.SEARCH, 
  new AutoQueueAdjustingExecutorBuilder(settings,
                        Names.SEARCH, searchThreadPoolSize(availableProcessors), 1000, 1000, 1000, 2000));

  builders.put(Names.MANAGEMENT, 
  new ScalingExecutorBuilder(Names.MANAGEMENT, 1, 5, TimeValue.timeValueMinutes(5)));

  builders.put(Names.LISTENER, 
  new FixedExecutorBuilder(settings, Names.LISTENER, halfProcMaxAt10, -1));

  builders.put(Names.FLUSH, 
  new ScalingExecutorBuilder(Names.FLUSH, 1, halfProcMaxAt5, TimeValue.timeValueMinutes(5)));

  builders.put(Names.REFRESH, 
  new ScalingExecutorBuilder(Names.REFRESH, 1, halfProcMaxAt10, TimeValue.timeValueMinutes(5)));

  builders.put(Names.WARMER, 
  new ScalingExecutorBuilder(Names.WARMER, 1, halfProcMaxAt5, TimeValue.timeValueMinutes(5)));

  builders.put(Names.SNAPSHOT, 
  new ScalingExecutorBuilder(Names.SNAPSHOT, 1, halfProcMaxAt5, TimeValue.timeValueMinutes(5)));

  builders.put(Names.FETCH_SHARD_STARTED, 
  new ScalingExecutorBuilder(Names.FETCH_SHARD_STARTED, 1, 2 * availableProcessors, TimeValue.timeValueMinutes(5)));

  builders.put(Names.FORCE_MERGE, 
  new FixedExecutorBuilder(settings, Names.FORCE_MERGE, 1, -1));

  builders.put(Names.FETCH_SHARD_STORE, 
  new ScalingExecutorBuilder(Names.FETCH_SHARD_STORE, 1, 2 * availableProcessors, TimeValue.timeValueMinutes(5)));
}

说明:

  • elasticsearch线程池根据作用的不同主要分为两大类 ScalingExecutor和FixedExecutor。
  • ScalingExecutor表示线程池中的线程数是动态可变的。
  • FixedExecutor表示线程池中的线程池是不可变的。


elasticsearch线程池分类

elasticsearch线程池的线程按照源码的实现来看分为FIXED和SCALING两大类,FIXED的意思是固定线程的数量(core thread个数 = max thread个数),SCALING的意思是动态调整线程数量(core thread个数 != max thread个数)。

FIXED

说明:大小固定设置的threadpool,它有一个queue来存放pending的请求,其中pool的大小默认是core*5,queue_size默认是-1(即是无限制)。

  • LISTENER:用作client的操作,默认大小halfProcMaxAt10,queue_size=-1无限制;

  • GET:用作get操作,默认大小availableProcessors,queue_size为1000;

  • INDEX:用作index或delete操作,默认大小availableProcessors,queue_size为200;

  • BULK:用作bulk操作,默认大小为availableProcessors,queue_size为200;

  • SEARCH:用作count或是search操作,默认大小((availableProcessors * 3) / 2) + 1;queue_size为1000;

  • SUGGEST:用作suggest操作,默认大小availableProcessors,queue_size为1000;

  • PERCOLATE:用作percolate,默认大小为availableProcessors,queue_size为1000;

  • FORCE_MERGE:用作force_merge操作(2.1之前叫做optimize),默认大小为1;


SCALING

说明:拥有可变大小的pool,其值可在1和设置值之间。

  • GENERIC:通用的操作,比如node的discovery,默认大小genericThreadPoolMax,默认keep alive时间是30sec;

  • MANAGEMENT:用作ES的管理,比如集群的管理;默认大小5,keep alive时间为5min;

  • FLUSH:用作flush操作,默认大小为halfProcMaxAt5,keep alive时间为5min;

  • REFRESH:用作refresh操作,默认大小为halfProcMaxAt10,keep alive时间为5min;

  • WARMER:用作index warm-up操作,默认大小为halfProcMaxAt5,keep alive时间为5min;

  • SNAPSHOT:用作snapshot操作,默认大小为halfProcMaxAt5,keep alive时间为5min;

  • FETCH_SHARD_STARTED:用作fetch shard开始操作,默认大小availableProcessors * 2,keep alive时间为5min;

  • FETCH_SHARD_STORE:用作fetch shard存储操作,默认大小availableProcessors * 2,keep alive时间为5min;


JDK的Executors

public class Executors {

    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

    public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>(),
                                      threadFactory);
    }

    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

    public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>(),
                                      threadFactory);
    }
}

说明:

  • Executors的newFixedThreadPool创建固定线程数量的线程池。
  • Executors的newCachedThreadPool创建可动态调整线程数量的线程池。
  • Executors创建的是ThreadPoolExecutor对象。


Elasticsearch的EsExecutors

public class EsExecutors {

    public static final Setting<Integer> PROCESSORS_SETTING =
        Setting.intSetting("processors", Runtime.getRuntime().availableProcessors(), 1, Property.NodeScope);

    public static int numberOfProcessors(final Settings settings) {
        return PROCESSORS_SETTING.get(settings);
    }

    public static EsThreadPoolExecutor newScaling(String name, int min, int max, long keepAliveTime, 
                          TimeUnit unit, ThreadFactory threadFactory, ThreadContext contextHolder) {
        ExecutorScalingQueue<Runnable> queue = new ExecutorScalingQueue<>();
        EsThreadPoolExecutor executor = new EsThreadPoolExecutor(name, min, max, keepAliveTime, 
                            unit, queue, threadFactory, new ForceQueuePolicy(), contextHolder);
        queue.executor = executor;
        return executor;
    }

    public static EsThreadPoolExecutor newFixed(String name, int size, int queueCapacity, 
                             ThreadFactory threadFactory, ThreadContext contextHolder) {
        BlockingQueue<Runnable> queue;
        if (queueCapacity < 0) {
            queue = ConcurrentCollections.newBlockingQueue();
        } else {
            queue = new SizeBlockingQueue<>(ConcurrentCollections.<Runnable>newBlockingQueue(), queueCapacity);
        }
        return new EsThreadPoolExecutor(name, size, size, 0, TimeUnit.MILLISECONDS, queue, 
                                        threadFactory, new EsAbortPolicy(), contextHolder);
    }

    public static EsThreadPoolExecutor newAutoQueueFixed(String name, int size, int initialQueueCapacity, int minQueueSize,
                                                         int maxQueueSize, int frameSize, TimeValue targetedResponseTime,
                                                         ThreadFactory threadFactory, ThreadContext contextHolder) {
        if (initialQueueCapacity <= 0) {
            throw new IllegalArgumentException("initial queue capacity for [" + name + "] executor must be positive, got: " +
                            initialQueueCapacity);
        }
        ResizableBlockingQueue<Runnable> queue =
                new ResizableBlockingQueue<>(ConcurrentCollections.<Runnable>newBlockingQueue(), initialQueueCapacity);
        return new QueueResizingEsThreadPoolExecutor(name, size, size, 0, TimeUnit.MILLISECONDS,
                queue, minQueueSize, maxQueueSize, TimedRunnable::new, frameSize, targetedResponseTime, threadFactory,
                new EsAbortPolicy(), contextHolder);
    }
}

说明:

  • newScaling()方法创建可扩展线程数量的线程池,淘汰策略使用ForceQueuePolicy。
  • newFixed()方法创建创建固定线程数量的线程池,淘汰策略使用EsAbortPolicy。
  • newAutoQueueFixed()方法创建固定线程数量但是Queue队列数量可以动态调整的线程池,淘汰策略使用EsAbortPolicy。。
  • EsExecutors内部创建的是EsThreadPoolExecutor对象。
  • EsExecutors的实现借鉴了JDK的Executors接口,给我们提供了自定Executors的思路。


EsExecutors的EsThreadPoolExecutor

public class EsThreadPoolExecutor extends ThreadPoolExecutor {
    EsThreadPoolExecutor(String name, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
            BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, ThreadContext contextHolder) {
        this(name, corePoolSize, maximumPoolSize, keepAliveTime, unit, 
             workQueue, threadFactory, new EsAbortPolicy(), contextHolder);
    }

    EsThreadPoolExecutor(String name, int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
            BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, XRejectedExecutionHandler handler,
            ThreadContext contextHolder) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
        this.name = name;
        this.contextHolder = contextHolder;
    }

    @Override
    public void execute(final Runnable command) {
        doExecute(wrapRunnable(command));
    }

    protected void doExecute(final Runnable command) {
        try {
            super.execute(command);
        } catch (EsRejectedExecutionException ex) {
            if (command instanceof AbstractRunnable) {
                try {
                    ((AbstractRunnable) command).onRejection(ex);
                } finally {
                    ((AbstractRunnable) command).onAfter();

                }
            } else {
                throw ex;
            }
        }
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        assert assertDefaultContext(r);
    }
}

说明:

  • EsThreadPoolExecutor继承自ThreadPoolExecutor对象,构造函数内部初始化ThreadPoolExecutor对象。
  • EsThreadPoolExecutor的核心的execute方法内部也是调用了ThreadPoolExecutor的execute方法。
  • EsThreadPoolExecutor重新了execute和afterExecute方法。
  • EsThreadPoolExecutor给我们提供了重写ThreadPoolExecutor的思路,值得学习。


EsExecutors的ThreadFactory

public class EsExecutors {

    public static String threadName(Settings settings, String ... names) {
        String namePrefix =
                Arrays
                        .stream(names)
                        .filter(name -> name != null)
                        .collect(Collectors.joining(".", "[", "]"));
        return threadName(settings, namePrefix);
    }

    public static ThreadFactory daemonThreadFactory(String namePrefix) {
        return new EsThreadFactory(namePrefix);
    }

    static class EsThreadFactory implements ThreadFactory {

        final ThreadGroup group;
        final AtomicInteger threadNumber = new AtomicInteger(1);
        final String namePrefix;

        EsThreadFactory(String namePrefix) {
            this.namePrefix = namePrefix;
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                    namePrefix + "[T#" + threadNumber.getAndIncrement() + "]",
                    0);
            t.setDaemon(true);
            return t;
        }
    }

    private EsExecutors() {
    }
}

说明:

  • 1.EsExecutors给我们提供一种创建线程工厂的标准方法,实现ThreadFactory接口重新newThread()方法。
  • 2.通过AtomicInteger threadNumber = new AtomicInteger(1)变量生成线程自增的线程id。
  • 3.线程池的线程都有具体意义的线程名非常重要有利于排查问题,非常推荐使用。


EsExecutors的AbortPolicy

public interface XRejectedExecutionHandler extends RejectedExecutionHandler {
    long rejected();
}

public class EsAbortPolicy implements XRejectedExecutionHandler {
    private final CounterMetric rejected = new CounterMetric();

    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        if (r instanceof AbstractRunnable) {
            if (((AbstractRunnable) r).isForceExecution()) {
                BlockingQueue<Runnable> queue = executor.getQueue();
                if (!(queue instanceof SizeBlockingQueue)) {
                    throw new IllegalStateException("forced execution, but expected a size queue");
                }
                try {
                    ((SizeBlockingQueue) queue).forcePut(r);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new IllegalStateException("forced execution, but got interrupted", e);
                }
                return;
            }
        }
        rejected.inc();
        throw new EsRejectedExecutionException("rejected execution of " + r + " on " + executor, executor.isShutdown());
    }

    public long rejected() {
        return rejected.count();
    }
}


static class ForceQueuePolicy implements XRejectedExecutionHandler {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            try {
                executor.getQueue().put(r);
            } catch (InterruptedException e) {
                throw new EsRejectedExecutionException(e);
            }
        }

        @Override
        public long rejected() {
            return 0;
        }
    }

说明:

  • EsAbortPolicy的过期策略提供了我们自定实现过期策略的案例。


相关实践学习
以电商场景为例搭建AI语义搜索应用
本实验旨在通过阿里云Elasticsearch结合阿里云搜索开发工作台AI模型服务,构建一个高效、精准的语义搜索系统,模拟电商场景,深入理解AI搜索技术原理并掌握其实现过程。
ElasticSearch 最新快速入门教程
本课程由千锋教育提供。全文搜索的需求非常大。而开源的解决办法Elasricsearch(Elastic)就是一个非常好的工具。目前是全文搜索引擎的首选。本系列教程由浅入深讲解了在CentOS7系统下如何搭建ElasticSearch,如何使用Kibana实现各种方式的搜索并详细分析了搜索的原理,最后讲解了在Java应用中如何集成ElasticSearch并实现搜索。 &nbsp;
目录
相关文章
|
缓存 监控 Java
深入Elasticsearch:线程池的原理与应用
深入Elasticsearch:线程池的原理与应用
|
消息中间件 存储 监控
Elasticsearch 线程池和队列问题,请先看这一篇
1、线程池相关线上实战问题 问题1:从Kafka消费数据导入 elasticsearch 时,批量 bulk 写入抛异常被拒绝。ES 集群四个节点,其中:两个节点node1和node4 thread pool bulk rejected 30多万条数据,es bulk thread pool 线程数8、队列200, Kafka写线程池 thread数2*cores+cores/2、队列数3。目前是想平衡一下写的速度和 es 处理的速度,不过现在还没有可用环境压测,想问有经验数据或方法参考吗?
Elasticsearch 线程池和队列问题,请先看这一篇
|
JSON 缓存 数据可视化
深入解读 Elasticsearch 热点线程 hot_threads
1、实战问题来源 问题1:大佬们 GET /_nodes/hot_threads 查看热线程的这个API有没有讲解请求结果的文章呢?返回一堆堆栈看不懂...... 问题2:ES集群就一台机器 CPU 爆高,但IO、heap_mem都正常。咋搞?hot_thread 我查了,报了一坨,SOS 死磕 Elasticsearch 知识星球微信群
深入解读 Elasticsearch 热点线程 hot_threads
|
Java
elasticsearch线程池介绍
转自:http://blog.csdn.net/opensure/article/details/51491815
1631 0
|
安全 Java Linux
Linux安装Elasticsearch详细教程
Linux安装Elasticsearch详细教程
2774 64
|
JSON 安全 数据可视化
Elasticsearch(es)在Windows系统上的安装与部署(含Kibana)
Kibana 是 Elastic Stack(原 ELK Stack)中的核心数据可视化工具,主要与 Elasticsearch 配合使用,提供强大的数据探索、分析和展示功能。elasticsearch安装在windows上一般是zip文件,解压到对应目录。文件,elasticsearch8.x以上版本是自动开启安全认证的。kibana安装在windows上一般是zip文件,解压到对应目录。elasticsearch的默认端口是9200,访问。默认用户是elastic,密码需要重置。
7106 0
|
NoSQL 关系型数据库 Redis
mall在linux环境下的部署(基于Docker容器),Docker安装mysql、redis、nginx、rabbitmq、elasticsearch、logstash、kibana、mongo
mall在linux环境下的部署(基于Docker容器),docker安装mysql、redis、nginx、rabbitmq、elasticsearch、logstash、kibana、mongodb、minio详细教程,拉取镜像、运行容器
2954 5
mall在linux环境下的部署(基于Docker容器),Docker安装mysql、redis、nginx、rabbitmq、elasticsearch、logstash、kibana、mongo
|
存储 安全 数据管理
如何在 Rocky Linux 8 上安装和配置 Elasticsearch
本文详细介绍了在 Rocky Linux 8 上安装和配置 Elasticsearch 的步骤,包括添加仓库、安装 Elasticsearch、配置文件修改、设置内存和文件描述符、启动和验证 Elasticsearch,以及常见问题的解决方法。通过这些步骤,你可以快速搭建起这个强大的分布式搜索和分析引擎。
838 5
|
存储 JSON Java
elasticsearch学习一:了解 ES,版本之间的对应。安装elasticsearch,kibana,head插件、elasticsearch-ik分词器。
这篇文章是关于Elasticsearch的学习指南,包括了解Elasticsearch、版本对应、安装运行Elasticsearch和Kibana、安装head插件和elasticsearch-ik分词器的步骤。
1734 0
elasticsearch学习一:了解 ES,版本之间的对应。安装elasticsearch,kibana,head插件、elasticsearch-ik分词器。
|
数据可视化 Docker 容器
一文教会你如何通过Docker安装elasticsearch和kibana 【详细过程+图解】
这篇文章提供了通过Docker安装Elasticsearch和Kibana的详细过程和图解,包括下载镜像、创建和启动容器、处理可能遇到的启动失败情况(如权限不足和配置文件错误)、测试Elasticsearch和Kibana的连接,以及解决空间不足的问题。文章还特别指出了配置文件中空格的重要性以及环境变量中字母大小写的问题。
一文教会你如何通过Docker安装elasticsearch和kibana 【详细过程+图解】

热门文章

最新文章