1、Zookeeper安装

 从Zookeeper官网下载,进入到bin目录下,在cms中执行zkServer就可以运行Zookeeper了。


Dubbo入门学习--Dubbo简单示例_xml


2、API接口

创建一个接口jar,此接口在服务提供者和服务消费者中使用

public interface IDemoServer {
String sayHello(String str);
}

3、服务提供者


applicationContext.xml中添加如下配置:


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd
">
<!--应用名称-->
<dubbo:application name="hello-world-app" />
<!--配置Zookeeper连接地址-->
<dubbo:registry protocol="zookeeper" address="localhost:2181" />
<!--服务协议-->
<dubbo:protocol name="dubbo"/>
<!--接口-->
<dubbo:service interface="com.tianjunwei.server.dubbo.service.IDemoServer"
ref="demoService" /> <!-- 和本地bean一样实现服务 -->
<!--实现类-->
<bean id="demoService" class="com.tianjunwei.server.dubbo.service.DemoServerImpl" />
</beans>

接口IDemoServer的实现类


public class DemoServerImpl implements IDemoServer {

public String sayHello(String str) {

return str;
}

}

Main函数启动提供服务:


public class Main {


public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "applicationProvider.xml" });
context.start();
while(true){

}
}

}

3、服务消费者


applicationContext.xml中如下配置:


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd
">
<!-- 消费方应用名-->
<dubbo:application name="consumer-of-helloworld-app" />
<!-- Zookeeper连接信息 -->
<dubbo:registry protocol="zookeeper" address="localhost:2181" />
<!-- 服务接口 -->
<dubbo:reference id="demoService" interface="com.tianjunwei.server.dubbo.service.IDemoServer"/>
</beans>

服务调用:


public class ChatAction {

@SuppressWarnings("resource")
public static void main(String[] args) throws InterruptedException{
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
context.start();
IDemoServer demoServer = (IDemoServer) context.getBean("demoService");
System.out.println("client:"+demoServer.sayBye("dubbo"));

}

}


运行结果:



client:dubbo



可以去官网https://github.com/alibaba/dubbo中参考示例程序。