本文共 2910 字,大约阅读时间需要 9 分钟。
当前环境:jdk1.8、eclipse、zookeeper3.4.13
直接使用简单demo中的父级xml
dubbo-api dubbo-api 0.0.1-SNAPSHOT
/** * @description 使用java方式创建dubbo项目--客户端 * @author hy * @date 2019-10-07 */public class Customer { public static void main( String[] args ) { // 当前应用配置 ApplicationConfig application = new ApplicationConfig(); application.setName("hello-world-app-customer"); // 连接注册中心配置 RegistryConfig registry = new RegistryConfig(); registry.setAddress("zookeeper://192.168.133.129:2181");//这里使用zookeeper作为注册中心 // 注意:ReferenceConfig为重对象,内部封装了与注册中心的连接,以及与服务提供方的连接 // 引用远程服务 ReferenceConfigreference = new ReferenceConfig (); // 此实例很重,封装了与注册中心的连接以及与提供者的连接,请自行缓存,否则可能造成内存和连接泄漏 reference.setApplication(application); reference.setRegistry(registry); // 多个注册中心可以用setRegistries() reference.setInterface(DemoService.class); reference.setVersion("1.0.0"); // 和本地bean一样使用xxxService DemoService demoService = reference.get(); // 注意:此代理对象内部封装了所有通讯细节,对象较重,请缓存复用 String say = demoService.say("World"); System.out.println(say); }}
当前的Customer可以按照xml中的配置依此配置即可
dubbo-api dubbo-api 0.0.1-SNAPSHOT
/** * @description 创建服务实现类 * @author hy * @date 2019-10-07 */public class DemoServiceImpl implements DemoService { @Override public String say(String context) { return "Hello "+context+" !"; }}
/** * @description 使用纯java方式配置dubbo--服务提供端 * @author hy * @date 2019-10-07 */public class Provider { public static void main(String[] args) throws IOException { // 服务实现 DemoService demoService = new DemoServiceImpl(); // 当前应用配置 ApplicationConfig application = new ApplicationConfig(); application.setName("hello-world-app-provider"); // 连接注册中心配置 RegistryConfig registry = new RegistryConfig(); registry.setAddress("zookeeper://192.168.133.129:2181");//这里使用zookeeper作为服务注册中心 // 服务提供者协议配置 ProtocolConfig protocol = new ProtocolConfig(); protocol.setName("dubbo"); protocol.setPort(20880); //protocol.setThreads(200); // 注意:ServiceConfig为重对象,内部封装了与注册中心的连接,以及开启服务端口 // 服务提供者暴露服务配置 ServiceConfigservice = new ServiceConfig (); // 此实例很重,封装了与注册中心的连接,请自行缓存,否则可能造成内存和连接泄漏 service.setApplication(application); service.setRegistry(registry); // 多个注册中心可以用setRegistries() service.setProtocol(protocol); // 多个协议可以用setProtocols() service.setInterface(DemoService.class); service.setRef(demoService); service.setVersion("1.0.0"); // 暴露及注册服务 service.export(); System.in.read(); //需要等待 }}
发现其中创建的配置其实就跟xml配置完全一致
1.其实当前java配置版和xml配置版基本上差不多,就是将对应的标签换成了对应的对象
以上纯属个人见解,如有问题请联系本人!
转载地址:http://theh.baihongyu.com/