1. 程式人生 > >dubbo之dubbo協議使用

dubbo之dubbo協議使用

dubbo

普通接口及實現類

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"直連地址.

相反,則通過註冊中心來獲取連接地址.


本文出自 “旅行者” 博客,請務必保留此出處http://881206524.blog.51cto.com/10315134/1923911

dubbo之dubbo協議使用