前言:咱們在使用dubbo的時候,習慣性配置的就是xml,咱們還能夠根據java代碼進行配置,話很少說,看下面的代碼java
1.提供者的java配置 緩存
import com.alibaba.dubbo.rpc.config.ApplicationConfig; import com.alibaba.dubbo.rpc.config.RegistryConfig; import com.alibaba.dubbo.rpc.config.ProviderConfig; import com.alibaba.dubbo.rpc.config.ServiceConfig; import com.xxx.XxxService; import com.xxx.XxxServiceImpl; // 服務的實現 XxxService xxxService = new XxxServiceImpl(); // 應用信息 ApplicationConfig application = new ApplicationConfig(); application.setName("xxx"); //註冊信息 RegistryConfig registry = new RegistryConfig(); registry.setAddress("10.20.130.230:9090"); registry.setUsername("aaa"); registry.setPassword("bbb"); // 用dubbo協議在20880端口暴露服務 ProtocolConfig protocol = new ProtocolConfig(); protocol.setName("dubbo"); protocol.setPort(20880); protocol.setThreads(200); // 注意:ServiceConfig保存serversocket實例並保持鏈接到registry,請將其緩存以得到性能。 // 導入配置 ServiceConfig<XxxService> service = new ServiceConfig<XxxService>(); service.setApplication(application); service.setRegistry(registry); // Use setRegistries() for multi-registry case service.setProtocol(protocol); // Use setProtocols() for multi-protocol case service.setInterface(XxxService.class); service.setRef(xxxService); service.setVersion("1.0.0"); // 執行配置 service.export();
2.消費者app
import com.alibaba.dubbo.rpc.config.ApplicationConfig; import com.alibaba.dubbo.rpc.config.RegistryConfig; import com.alibaba.dubbo.rpc.config.ConsumerConfig; import com.alibaba.dubbo.rpc.config.ReferenceConfig; import com.xxx.XxxService; // 應用信息 ApplicationConfig application = new ApplicationConfig(); application.setName("yyy"); // 註冊中心發現 RegistryConfig registry = new RegistryConfig(); registry.setAddress("10.20.130.230:9090"); registry.setUsername("aaa"); registry.setPassword("bbb"); // 註釋:ReferenceConfig保持與註冊中心和提供者的鏈接,請將其緩存以得到性能。 // 引用遠程服務 ReferenceConfig<XxxService> reference = new ReferenceConfig<XxxService>(); // In case of memory leak, please cache. reference.setApplication(application); reference.setRegistry(registry); reference.setInterface(XxxService.class); reference.setVersion("1.0.0"); // 使用 xxxService 做爲一個bean XxxService xxxService = reference.get(); // NOTES: Please cache this proxy instance.
不過官方仍是推薦xml的配置方式進行配置,由於可拓展性比較強。socket