普通接口及實現類
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"直連地址.
相反,則通過注冊中心來獲取連接地址.
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。