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