原文地址:https://www.cnblogs.com/UncleYong/p/10732747.html
接口需求
客户端输入uncleyong(当然,也可以输入其它字符串),服务端返回hello uncleyong
开发环境
jdk + idea + maven + zookeeper
jdk安装
idea安装
maven安装
zookeeper安装
common开发
idea中创建模块dubbo-common
存放公共的实体类、接口
package com.uncleyong.dubbotest.service;
public interface SayHelloToClient {
public String sayHello(String name);
}
然后mvn install打包,供provider及consumer在pom文件中引包
provider开发
idea中创建模块dubbo_provider
创建实现类
package com.uncleyong.dubbotest.service.impl;
import com.uncleyong.dubbotest.service.SayHelloToClient;
public class SayHelloToClientImpl implements SayHelloToClient {
public String sayHello(String name){
System.out.println("from client :" + name);
return "hello, " + name;
}
}
配置文件,provider.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://dubbo.apache.org/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">
创建主运行文件,ProviderMain
package com.uncleyong.dubbotest.main;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ProviderMain {
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[] {"provider.xml"});
context.start();
System.out.println("注册成功,如想退出,按任意键退出");
System.in.read(); // 按任意键退出
}
}
consumer开发
idea中创建模块dubbo_consumer
主运行文件
package com.uncleyong.dubbotest.main;
import com.uncleyong.dubbotest.service.SayHelloToClient;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Scanner;
public class ConsumerMain {
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[] {"consumer.xml"});
context.start();
// 获取远程服务代理
SayHelloToClient say = (SayHelloToClient) context.getBean("sayhellotoclient");
// 执行远程方法
String res = say.sayHello("UncleYong");
// 显示调用结果
System.out.println(res);
new Scanner(System.in).next();
}
}
配置文件,consumer.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://dubbo.apache.org/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://dubbo.apache.org/schema/dubbo http://dubbo.apache.org/schema/dubbo/dubbo.xsd">
运行结果及项目源码
先启动zookeeper,进入zookeeper的bin目录,点击【zkServer.cmd】
启动provider
服务注册成功
启动consumer,可以看到输出了结果
在provider端,也可以看到客户端发过来的消息
至此,开发完成。
项目完整源码