Dubbo[]是一個分佈式服務框架,致力於提供高性能和透明化的RPC遠程服務調用方案,以及SOA服務治理方案。java
其核心部分包括:git
![]() |
Dubbo採用全Spring配置方式。透明化接入應用,相應用沒有不論什麼API侵入,僅僅需用Spring載入Dubbo的配置就能夠,Dubbo基於Spring的Schema擴展進行載入。 |
定義服務接口: (該接口需單獨打包,在服務提供方和消費方共享)github
package
com.alibaba.dubbo.demo;
public
interface
DemoService {
String sayHello(String name);
}
|
在服務提供方實現接口:(對服務消費方隱藏實現)spring
package
com.alibaba.dubbo.demo.provider;
import
com.alibaba.dubbo.demo.DemoService;
public
class
DemoServiceImpl
implements
DemoService {
public
String sayHello(String name) {
return
"Hello "
+ name;
}
}
|
用Spring配置聲明暴露服務:app
<?
xml
version
=
"1.0"
encoding
=
"UTF-8"
?
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協議在20880port暴露服務 -->
<
dubbo:protocol
name
=
"dubbo"
port
=
"20880"
/>
<!-- 聲明需要暴露的服務接口 -->
<
dubbo:service
interface
=
"com.alibaba.dubbo.demo.DemoService"
ref
=
"demoService"
/>
<!-- 和本地bean同樣實現服務 -->
<
bean
id
=
"demoService"
class
=
"com.alibaba.dubbo.demo.provider.DemoServiceImpl"
/>
</
beans
>
|
載入Spring配置:框架
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public
class
Provider {
public
static
void
main(String[] args)
throws
Exception {
ClassPathXmlApplicationContext context =
new
ClassPathXmlApplicationContext(
new
String[] {
"http://10.20.160.198/wiki/display/dubbo/provider.xml"
});
context.start();
System.in.read();
// 按隨意鍵退出
}
}
|
經過Spring配置引用遠程服務:分佈式
<?
xml
version
=
"1.0"
encoding
=
"UTF-8"
?>
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"
/>
<!-- 使用multicast廣播註冊中心暴露發現服務地址 -->
<
dubbo:registry
address
=
"multicast://224.5.6.7:1234"
/>
<!-- 生成遠程服務代理。可以和本地bean同樣使用demoService -->
<
dubbo:reference
id
=
"demoService"
interface
=
"com.alibaba.dubbo.demo.DemoService"
/>
</
beans
>
|
載入Spring配置,並調用遠程服務:(也可以使用IoC注入)ide
import
org.springframework.context.support.ClassPathXmlApplicationContext;
import
com.alibaba.dubbo.demo.DemoService;
public
class
Consumer {
public
static
void
main(String[] args)
throws
Exception {
ClassPathXmlApplicationContext context =
new
ClassPathXmlApplicationContext(
new
String[] {
"http://10.20.160.198/wiki/display/dubbo/consumer.xml"
});
context.start();
DemoService demoService = (DemoService)context.getBean(
"demoService"
);
// 獲取遠程服務代理
String hello = demoService.sayHello(
"world"
);
// 運行遠程方法
System.out.println( hello );
// 顯示調用結果
}
}
|
版權聲明:本文博客原創文章,博客,未經贊成,不得轉載。性能