TransportClient使用

TransportClient初始化


Settings setting = Settings.builder().put("cluster.name", clusterName).put("client.transport.sniff", true).build(); 
System.setProperty("es.set.netty.runtime.available.processors", "false");
TransportClient transportClient = new PreBuiltTransportClient(setting);
serverAddresses.forEach(transportClient::addTransportAddress);

上面客户端的初始化的过程比较简单,但是却基本包含了es的客户端初始化所需要的关键参数。

  • 指定集群参数
  • 指定是否要开启探嗅
  • 是否指定底层netty的group数量
  • 连接集群的ip

PreBuiltTransportClient这个类是TransportClient前置配置builder,将相关的配置初始化。

 /**
     * Creates a new transport client with pre-installed plugins.
     *
     * @param settings            the settings passed to this transport client
     * @param plugins             a collection of additional plugins to run with this client
     * @param hostFailureListener a failure listener that is invoked if a node is disconnected; this can be null
     */
    public PreBuiltTransportClient(
        Settings settings,
        Collection> plugins,
        HostFailureListener hostFailureListener) {
        super(settings, Settings.EMPTY, addPlugins(plugins, PRE_INSTALLED_PLUGINS), hostFailureListener);
    }

从上面构造器看出,这个类啥都没干,就调了下他的父类,并传入一些初始化的参数和默认的插件类。

private static final Collection> PRE_INSTALLED_PLUGINS =
        Collections.unmodifiableList(
            Arrays.asList(
                Netty3Plugin.class,
                Netty4Plugin.class,
                ReindexPlugin.class,
                PercolatorPlugin.class,
                MustachePlugin.class));

上面主要是关注的是网络通信框架是netty框架。
根据上面分析,真正进行初始化的是TransportClient,PreBuiltTransportClient只是一个壳而已。下面重点分析TransportClient


/**
     * Creates a new TransportClient with the given settings, defaults and plugins.
     * @param settings the client settings
     * @param defaultSettings default settings that are merged after the plugins have added it's additional settings.
     * @param plugins the client plugins
     */
    protected TransportClient(Settings settings, Settings defaultSettings, Collection> plugins,
                              HostFailureListener hostFailureListener) {
        this(buildTemplate(settings, defaultSettings, plugins, hostFailureListener));
    }

可以看出构造TransportClient构造是通过一个模版方法实现,所以buildTemplate是最核心的方法,我们主要分析下这个模版方法做了些什么。

TransportClient#buildTemplate

因为代码量比较大,就不贴了,主要做了几件事:

  • 插件类进行初始化
  • 配置进行初始化
  • Injector进行管理所有初始化的bean,类似spring的bean管理
  • netty框架进行初始化并启动
  • 还有一些线程池的配置初始化

你可能感兴趣的:(elasticsearch)