普通接口及实现类
public interface DemoService
{
String sayHello(String msg);
}
public class DemoServiceImpl implements DemoService
{
public String sayHello(String msg)
{
return "hello " + msg;
}
}
服务提供者配置
<?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"/>
<!-- 使用multicast广播注册中心暴露服务地址 -->
<!--<dubbo:registry address="multicast://224.5.6.7:1234"/>-->
<!-- 用dubbo协议在20880端口暴露服务 -->
<dubbo:protocol name="dubbo" port="20880"/>
<!-- 声明需要暴露的服务接口 -->
<dubbo:service interface="com.dubbo.dubbo.DemoService" ref="demoService" registry="N/A"/>
<!-- 和本地bean一样实现服务 -->
<bean id="demoService" class="com.dubbo.dubbo.DemoServiceImpl"/>
</beans>
服务消费者配置
<?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-consumer"/>
<!-- 使用multicast广播注册中心暴露服务地址 -->
<!-- <dubbo:registry address="multicast://224.5.6.7:1234"/> -->
<!-- 声明需要暴露的服务接口 -->
<dubbo:reference interface="com.dubbo.dubbo.DemoService" id="demoService" url="dubbo://localhost:20880"/>
</beans>
运行测试
public class Provider
{
public static void main(String[] args) throws Exception
{
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("dubbo-dubbo-provider.xml");
context.start();
System.in.read(); // 按任意键退出
}
}
public class Consumer
{
public static void main(String[] args) throws Exception
{
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("dubbo-dubbo-consumer.xml");
context.start();
DemoService demoService = (DemoService)context.getBean("demoService"); // 获取远程服务代理
String hello = demoService.sayHello("world"); // 执行远程方法
System.err.println( hello ); // 显示调用结果
}
}
直连模式
服务提供者,不用将服务注册到注册中心,并在dubbo:service配置中增加registry="N/A";
同时,服务消费者也不需要通过注册中心发现服务,并在dubbo:reference配置中增加url="dubbo://localhost:20880"直连地址.
相反,则通过注册中心来获取连接地址.