Elasticsearch 中的 Guice

小旋鋒發表於2018-08-30

前言

Elasticsearch 原始碼中使用了Guice框架進行依賴注入. 為了方便閱讀原始碼, 此處我先通過模仿ES guice的使用方式簡單寫了一個基本Demo 方便理解, 之後再來理一下ES的Guice使用. 編寫的測試類原理圖如下:

ES Guice Demo

總共有兩個Module,一個是ToolModule,用於繫結IAnimal介面、ITool介面以及Map物件. 另一個是HumanModule 用於繫結Person物件。

其中Person的建構函式通過 @Inject 註解注入其他例項

gradle 需要引入的 Jar 包

compile group: 'com.google.inject.extensions', name: 'guice-multibindings', version: '4.2.0'
compile group: 'com.google.inject', name: 'guice', version: '4.2.0'
複製程式碼

1、Demo

iTool介面與實現類

public interface ITool {
    public void doWork();
}
複製程式碼
import com.whirly.guice.example.ITool;

public class IToolImpl implements ITool {
    @Override
    public void doWork() {
        System.out.println("use tool to work");
    }
}
複製程式碼

IAnimal 介面與實現類

public interface IAnimal {
    void work();
}
複製程式碼
public class IAnimalImpl implements IAnimal {
    @Override
    public void work() {
        System.out.println("animals can also do work");
    }
}
複製程式碼

ToolModule的實現, 它綁了三個例項

public class ToolModule extends AbstractModule {

    @Override
    protected void configure() {
        //此處注入的例項可以注入到其他類的建構函式中, 只要那個類使用@Inject進行注入即可
        bind(IAnimal.class).to(IAnimalImpl.class);
        bind(ITool.class).to(IToolImpl.class);

        // 注入Map例項
        MapBinder<String, String> mapBinder = MapBinder.newMapBinder(binder(), String.class, String.class);
        mapBinder.addBinding("test1").toInstance("test1");
        mapBinder.addBinding("test2").toInstance("test2");
    }
}
複製程式碼

bind(IAnimal.class).to(IAnimalImpl.class);bind(ITool.class).to(IToolImpl.class); 是將介面與其具體實現繫結起來

MapBinder<String,String> mapBinder =MapBinder.newMapBinder(binder(), String.class, String.class);mapBinder.addBinding("test1").toInstance("test1");mapBinder.addBinding("test2").toInstance("test2"); 則是完成Map的繫結.

後面來看看Person類和HumanModule

Person 類

public class Person {

    private IAnimal iAnimal;
    private ITool iTool;
    private Map<String, String> map;

    @Inject
    public Person(IAnimal iAnimal, ITool iTool, Map<String, String> map) {
        this.iAnimal = iAnimal;
        this.iTool = iTool;
        this.map = map;
    }

    public void startwork() {
        iTool.doWork();
        iAnimal.work();
        for (Map.Entry entry : map.entrySet()) {
            System.out.println("注入的map 是 " + entry.getKey() + " value " + entry.getValue());
        }
    }
}
複製程式碼

Person 類中由 IAnimalIToolMap<String, String> 這三個介面定義的變數,物件將通過 @Inject 從構造方法中注入進來

public class HumanModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(Person.class).asEagerSingleton();
    }
}
複製程式碼

Person類的建構函式是通過注入的方式,注入物件例項的

最後 CustomModuleBuilder 進行統一管理所有的Module,例項化所有Module中的物件. 完成依賴注入。

這裡的CustomModuleBuilder是修改自Elasticsearch中的ModulesBuilder,其原理是一樣的。

就是一個迭代器,內部封裝的是Module集合, 統一管理所有的Module

CustomModuleBuilder 統一管理 Module

public class CustomModuleBuilder implements Iterable<Module> {

    private final List<Module> modules = new ArrayList<>();

    public CustomModuleBuilder add(Module... newModules) {
        for (Module module : newModules) {
            modules.add(module);
        }
        return this;
    }

    @Override
    public Iterator<Module> iterator() {
        return modules.iterator();
    }

    public Injector createInjector() {
        Injector injector = Guice.createInjector(modules);
        return injector;
    }
}
複製程式碼

這樣就可以從Main方法是如何進行使用的

Main 方法

public class Main {
    public static void main(String[] args) {
        CustomModuleBuilder moduleBuilder = new CustomModuleBuilder();
        moduleBuilder.add(new ToolModule());
        moduleBuilder.add(new HumanModule());
        Injector injector = moduleBuilder.createInjector();
        Person person = injector.getInstance(Person.class);
        person.startwork();
    }
}
複製程式碼

執行結果

use tool to work
animals can also do work
注入的map 是 test1 value test1
注入的map 是 test2 value test2
複製程式碼

通過CustomModuleBuilder 的createInjector獲取Injector 物件, 根據Injector 物件取相應的具體例項物件.

2、ES 中Guice的使用

ES中TransportClient初始化時的Guice的使用是這樣的, 如下圖所示

ES中TransportClient初始化時的Guice的使用(ES版本不是6.3.2)

TransportClient的初始化程式碼

Elasticsearch 6.3.2

private static ClientTemplate buildTemplate(Settings providedSettings, Settings defaultSettings,
                                            Collection<Class<? extends Plugin>> plugins, HostFailureListener failureListner) {
    // 省略 ...
    try {
        // 省略 ...

        // 建立一個迭代器, 然後將各個Module通過add方法加入進去
        ModulesBuilder modules = new ModulesBuilder();
        // plugin modules must be added here, before others or we can get crazy injection errors...
        for (Module pluginModule : pluginsService.createGuiceModules()) {
            modules.add(pluginModule);
        }
        modules.add(b -> b.bind(ThreadPool.class).toInstance(threadPool));
        ActionModule actionModule = new ActionModule(true, settings, null, settingsModule.getIndexScopedSettings(),
                settingsModule.getClusterSettings(), settingsModule.getSettingsFilter(), threadPool,
                pluginsService.filterPlugins(ActionPlugin.class), null, null, null);
        modules.add(actionModule);

        CircuitBreakerService circuitBreakerService = Node.createCircuitBreakerService(settingsModule.getSettings(),
            settingsModule.getClusterSettings());
        resourcesToClose.add(circuitBreakerService);
        PageCacheRecycler pageCacheRecycler = new PageCacheRecycler(settings);
        BigArrays bigArrays = new BigArrays(pageCacheRecycler, circuitBreakerService);
        resourcesToClose.add(bigArrays);
        modules.add(settingsModule);
        
        NetworkModule networkModule = new NetworkModule(settings, true, pluginsService.filterPlugins(NetworkPlugin.class), threadPool,
            bigArrays, pageCacheRecycler, circuitBreakerService, namedWriteableRegistry, xContentRegistry, networkService, null);
        final Transport transport = networkModule.getTransportSupplier().get();
        final TransportService transportService = new TransportService(settings, transport, threadPool,
            networkModule.getTransportInterceptor(),
            boundTransportAddress -> DiscoveryNode.createLocal(settings, new TransportAddress(TransportAddress.META_ADDRESS, 0),
                UUIDs.randomBase64UUID()), null, Collections.emptySet());
        modules.add((b -> {
            b.bind(BigArrays.class).toInstance(bigArrays);
            b.bind(PluginsService.class).toInstance(pluginsService);
            b.bind(CircuitBreakerService.class).toInstance(circuitBreakerService);
            b.bind(NamedWriteableRegistry.class).toInstance(namedWriteableRegistry);
            b.bind(Transport.class).toInstance(transport);
            b.bind(TransportService.class).toInstance(transportService);
            b.bind(NetworkService.class).toInstance(networkService);
        }));

        // 注入所有module下的例項
        Injector injector = modules.createInjector();
        final TransportClientNodesService nodesService =
            new TransportClientNodesService(settings, transportService, threadPool, failureListner == null
                ? (t, e) -> {} : failureListner);

        // construct the list of client actions
        final List<ActionPlugin> actionPlugins = pluginsService.filterPlugins(ActionPlugin.class);
        final List<GenericAction> clientActions =
                actionPlugins.stream().flatMap(p -> p.getClientActions().stream()).collect(Collectors.toList());
        // add all the base actions
        final List<? extends GenericAction<?, ?>> baseActions =
                actionModule.getActions().values().stream().map(ActionPlugin.ActionHandler::getAction).collect(Collectors.toList());
        clientActions.addAll(baseActions);
        final TransportProxyClient proxy = new TransportProxyClient(settings, transportService, nodesService, clientActions);

        List<LifecycleComponent> pluginLifecycleComponents = new ArrayList<>(pluginsService.getGuiceServiceClasses().stream()
            .map(injector::getInstance).collect(Collectors.toList()));
        resourcesToClose.addAll(pluginLifecycleComponents);

        // 啟動服務
        transportService.start();
        transportService.acceptIncomingRequests();

        ClientTemplate transportClient = new ClientTemplate(injector, pluginLifecycleComponents, nodesService, proxy, namedWriteableRegistry);
        resourcesToClose.clear();
        return transportClient;
    } finally {
        IOUtils.closeWhileHandlingException(resourcesToClose);
    }
}
複製程式碼

可以看到確實是先通 過ModulesBuilder modules = new ModulesBuilder() 建立一個迭代器, 然後將各個Module通過add方法加入進去, 最後通過 Injector injector = modules.createInjector(); 建立Injector物件, 之後便可根據Injector物件去獲取例項了.

各個Module會繫結自己所需要的例項, 這裡以 SettingsModule 舉例:

public class SettingsModule extends AbstractModule {
    private final Settings settings;
    private final Set<String> settingsFilterPattern = new HashSet<>();
    private final Map<String, Setting<?>> nodeSettings = new HashMap<>();
    private final Map<String, Setting<?>> indexSettings = new HashMap<>();
    private final Logger logger;
    private final IndexScopedSettings indexScopedSettings;
    private final ClusterSettings clusterSettings;
    private final SettingsFilter settingsFilter;

    public SettingsModule(Settings settings, Setting<?>... additionalSettings) {
        this(settings, Arrays.asList(additionalSettings), Collections.emptyList());
    }

    @Override
    public void configure(Binder binder) {
        binder.bind(Settings.class).toInstance(settings);
        binder.bind(SettingsFilter.class).toInstance(settingsFilter);
        binder.bind(ClusterSettings.class).toInstance(clusterSettings);
        binder.bind(IndexScopedSettings.class).toInstance(indexScopedSettings);
    }
    
    //...
}
複製程式碼

可以看到它繫結了四個,分別是 Settings.class,SettingsFilter.class,ClusterSettings.class,IndexScopedSettings.class

它們的例項物件都可以通過Injector來獲取

小結

示例程式碼可在 github.com/whirlys/ela… 處下載

參考:
kason_zhang Elasticsearch Guice 的使用


更多內容請訪問我的個人部落格:laijianfeng.org/

開啟微信掃一掃,關注【小旋鋒】微信公眾號,及時接收博文推送

小旋鋒的微信公眾號

相關文章