有的时候我们不想和spring集成,也不想使用netty,可以使用dubbo api的方式手动构建服务提供者,服务消费者。
一、依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>dubbo</artifactId> <version>2.6.0</version> <exclusions> <exclusion> <artifactId>spring-context</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-beans</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-web</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>netty</artifactId> <groupId>org.jboss.netty</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.github.sgroschupf</groupId> <artifactId>zkclient</artifactId> <version>0.1</version> </dependency>
可以看到我已经把所有spring依赖和netty依赖全部排除了。引入zkclient是因为dubbo这个版本本身不带连接zkclient的jar。
二、服务
public interface HelloService { String hello();}
public class HelloServiceImpl implements HelloService { public String hello() { return "hello"; }}
三、构建dubbo服务提供者
public class Provider { public static void main(String[] args) throws IOException { HelloServiceImpl helloService = new HelloServiceImpl(); // 当前应用配置 ApplicationConfig application = new ApplicationConfig(); application.setName("hello"); // 连接注册中心配置 RegistryConfig registry = new RegistryConfig(); registry.setAddress("zookeeper://127.0.0.1:2181"); // registry.setUsername("aaa"); //registry.setPassword("bbb"); // 服务提供者协议配置 ProtocolConfig protocol = new ProtocolConfig(); protocol.setName("rmi"); // 使用jdk的RMI,替代netty protocol.setPort(8888); protocol.setThreads(10); // 注意:ServiceConfig为重对象,内部封装了与注册中心的连接,以及开启服务端口// 服务提供者暴露服务配置 ServiceConfig<HelloService> service = new ServiceConfig<HelloService>(); // 此实例很重,封装了与注册中心的连接,请自行缓存,否则可能造成内存和连接泄漏 service.setApplication(application); service.setRegistry(registry); // 多个注册中心可以用setRegistries() service.setProtocol(protocol); // 多个协议可以用setProtocols() service.setInterface(HelloService.class); service.setRef(helloService); service.setVersion("1.0.0");// 暴露及注册服务 service.export(); System.out.println("启动成功"); }}
四、构建dubbo服务消费者
public class Consumer { public static void main(String[] args) { // 当前应用配置 ApplicationConfig application = new ApplicationConfig(); application.setName("consumerA"); // 连接注册中心配置 RegistryConfig registry = new RegistryConfig(); registry.setAddress("zookeeper://127.0.0.1:2181"); // 注意:ReferenceConfig为重对象,内部封装了与注册中心的连接,以及与服务提供方的连接 // 引用远程服务 ReferenceConfig<HelloService> reference = new ReferenceConfig<HelloService>(); // 此实例很重,封装了与注册中心的连接以及与提供者的连接,请自行缓存,否则可能造成内存和连接泄漏 reference.setApplication(application); reference.setRegistry(registry); // 多个注册中心可以用setRegistries() reference.setInterface(HelloService.class); reference.setVersion("1.0.0"); // 和本地bean一样使用xxxService HelloService helloService = reference.get(); // 注意:此代理对象内部封装了所有通讯细节,对象较重,请缓存复用 String str = helloService.hello(); System.out.println(str); }}
输出结果:
hello