Dubbo經常使用使用方式你們都比較熟悉,肯定好服務的與服務之間調用關係,肯定好相關接口參數,基於spring配置好,啓動provider,而後啓動consumer去調用相關服務。但有這樣的一種場景:html
先來看第一種場景,能夠經過配置group 的方式實現同一個服務的不一樣實現版本:spring
提供者dubbo端配置: <dubbo:service interface="com.HelloService" group="groupA" ref="helloService" /> 消費者consumer配置: <dubbo:reference id="helloService"interface="com.HelloService" group="groupA"/> 說明:只有相同group的才能進行匹配,若要實現消費者任意調用提供者的某個服務,只須要把group設置爲「*」,即: <dubbo:reference interface="com.HelloService" group="*" id="helloService"/>
須要在實際使用時,構造出Consumer端的服務類,並經過上述的group的方式區分不一樣的服務實現,以下:緩存
public HelloService getInvokeService(String group) { ApplicationConfig application = new ApplicationConfig(); application.setName("dubboConsumer"); RegistryConfig registry = new RegistryConfig(); registry.setAddress("127.0.0.1:2181"); registry.setProtocol("zookeeper"); ReferenceConfig<HelloService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setApplication(application); referenceConfig.setRegistry(registry); referenceConfig.setGroup(group); referenceConfig.setInterface(HelloService.class); return referenceConfig.get(); }
上述實現已經能夠知足咱們提出的兩個要求,可是存在性能問題,由於每次調用該方法,都須要從新生成一個新的ReferenceConfig,而且調用get()方法獲取一個代理的實現,該實現封裝了與註冊中心的鏈接以及與提供者的鏈接。爲了可以重用該鏈接,能夠將其緩存,這裏使用dubbo內置的簡單緩存工具類進行緩存,實現代碼以下:性能優化
public HelloService getInvokeService(String group) { ApplicationConfig application = new ApplicationConfig(); application.setName("dubboConsumer"); RegistryConfig registry = new RegistryConfig(); registry.setAddress("127.0.0.1:2181"); registry.setProtocol("zookeeper"); ReferenceConfig<HelloService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setApplication(application); referenceConfig.setRegistry(registry); referenceConfig.setGroup(group); referenceConfig.setInterface(HelloService.class); ReferenceConfigCache cache = ReferenceConfigCache.getCache(); return cache.get(referenceConfig); }
參考文獻:Dubbo高級特性實踐-泛化調用app