Java 语言定义服务

示例使用 Spring XML 配置方式进行演示。

除此之外,Dubbo Java 还提供了包括注解、API、配置文件、spring boot等多种启动与接入方式,具体可参见配置章节具体描述。

下载示例代码

示例代码在 dubbo-samples

  1. 下载源码
  1. $ git clone -b master https://github.com/apache/dubbo-samples.git
  1. 进入示例目录
  1. $ cd dubbo-samples/dubbo-samples-basic

快速运行示例

在 dubbo-samples-basic 目录

  1. 编译 Provider
  1. $ mvn clean compile -Pprovider
  1. 运行 Provider
  1. $ java -jar ./target/provider.jar
  1. 编译 Consumer
  1. $ mvn clean compile -Pconsumer
  1. 运行 consumer
  1. $ java -jar ./target/consumer.jar

详细解释

定义服务接口

DemoService.java

  1. package org.apache.dubbo.samples.basic.api;
  2. public interface DemoService {
  3. String sayHello(String name);
  4. }

在服务提供方实现接口

DemoServiceImpl.java

  1. public class DemoServiceImpl implements DemoService {
  2. @Override
  3. public String sayHello(String name) {
  4. System.out.println("[" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "] Hello " + name +
  5. ", request from consumer: " + RpcContext.getContext().getRemoteAddress());
  6. return "Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress();
  7. }
  8. }

用 Spring 配置声明暴露服务

provider.xml:

  1. <bean id="demoService" class="org.apache.dubbo.samples.basic.impl.DemoServiceImpl"/>
  2. <dubbo:service interface="org.apache.dubbo.samples.basic.api.DemoService" ref="demoService"/>

服务消费者

引用远程服务

consumer.xml:

  1. <dubbo:reference id="demoService" check="true" interface="org.apache.dubbo.samples.basic.api.DemoService"/>

加载Spring配置,并调用远程服务

Consumer.java

  1. public static void main(String[] args) {
  2. ...
  3. DemoService demoService = (DemoService) context.getBean("demoService");
  4. String hello = demoService.sayHello("world");
  5. System.out.println(hello);
  6. }

最后修改 September 21, 2021: Bug fix miss mialbox (#953) (57cf51b)