在网上看了一上午,没找到好的dubbo实例,把官网上的细致的看了一篇,把实现流程写出来,大家一起学习。
首先 ,建两个maven项目,一个是服务提供方,一个是消费方。
定义一个服务接口
package com.xqn;
public interface DemoService{
String sayHello(String message);
}
实现这个接口
package com.xqn.impl;
public class DemoServeiceImpl implements DemoSevice{
@Override
public String sayHello(String message) {
return "Hello"+message;
}
}
用spring配置声明暴露服务
<?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="dubbo_provider" />
<!-- 使用multicast广播注册中心暴露服务地址 -->
<dubbo:registry address="multicast://224.5.6.7:1234" />
<!-- 用dubbo协议在20880端口暴露服务 -->
<dubbo:protocol name="dubbo" port="20880" />
<!-- 声明需要暴露的服务接口 -->
<dubbo:service interface="com.xqn.DemoService" ref="demoService" />
<!-- 和本地bean一样实现服务 -->
<bean id="demoService" class="com.xqn.impl.DemoServiceImpl" />
</beans>
最后,加载spring配置
package dubboSample;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestService{
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"applicationContext"});
while(true);
}
}
代码结构如图所示;
服务方建好后,开始建消费者方。两个maven项目差不多,修改一下spring配置声明
<?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="dubbo_consumer" />
<!-- 使用multicast广播注册中心暴露发现服务地址 -->
<dubbo:registry address="multicast://224.5.6.7:1234" />
<!-- 生成远程服务代理,可以和本地bean一样使用demoService -->
<dubbo:reference id="demoService" interface="com.xqn.DemoService" />
</beans>
同样加载spring配置
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestService{
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"applicationCtx.xml"});
context.start();
DemoService demoService = (DemoService)context.getBean("demoService"); // 获取远程服务代理
String hello = demoService.sayHello("world"); // 执行远程方法
System.out.println( hello ); // 显示调用结果
}
}
消费者代码结构:
上述就是一个简单的dubbo实例,大家可以参考官网文档进行练习
官网文档地址:http://dubbo.io/User+Guide-zh.htm
希望大家可以从这篇文章中学到东西
希望大家可以从这篇文章中学到东西