1. 項目結構
假設項目分為三個模塊:
api:定義服務接口
provider:服務提供者
consumer:服務消費者
2. 依賴配置
在 pom.xml
中添加 Dubbo 和注冊中心(如 Nacos)的依賴:
<dependency><groupId>org.apache.dubbo</groupId><artifactId>dubbo-spring-boot-starter</artifactId><version>3.0.2</version>
</dependency>
<dependency><groupId>com.alibaba.nacos</groupId><artifactId>nacos-client</artifactId><version>2.0.3</version>
</dependency>
3. 定義服務接口(api 模塊)
創建一個服務接口:
package com.example.api;public interface HelloService {String sayHello(String name);
}
4. 服務提供者(provider 模塊)
4.1 實現服務接口
package com.example.provider;import com.example.api.HelloService;
import org.apache.dubbo.config.annotation.Service;@Service(version = "1.0.0")
public class HelloServiceImpl implements HelloService {@Overridepublic String sayHello(String name) {return "Hello, " + name;}
}
4.2 配置 Dubbo
在 application.properties
中配置 Dubbo 和注冊中心:
properties
dubbo.application.name=hello-service-provider
dubbo.registry.address=nacos://127.0.0.1:8848
dubbo.protocol.name=dubbo
dubbo.protocol.port=20880
5. 服務消費者(consumer 模塊)
5.1 引用服務接口
在 application.properties
中配置 Dubbo 和注冊中心:
properties
dubbo.application.name=hello-service-consumer
dubbo.registry.address=nacos://127.0.0.1:8848
5.2 調用服務
package com.example.consumer;import com.example.api.HelloService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HelloController {@Reference(version = "1.0.0")private HelloService helloService;@GetMapping("/sayHello")public String sayHello(@RequestParam String name) {return helloService.sayHello(name);}
}
6. 啟動項目
啟動 Nacos 注冊中心。
啟動服務提供者模塊(provider)。
啟動服務消費者模塊(consumer)。
訪問
http://localhost:8080/sayHello?name=Kimi
,即可看到返回結果。
7. 泛化調用示例(可選)
如果需要泛化調用,可以在消費者端使用 GenericService
:
package com.example.consumer;import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.rpc.service.GenericService;public class GenericConsumer {public static void main(String[] args) {ReferenceConfig<GenericService> reference = new ReferenceConfig<>();reference.setInterface("com.example.api.HelloService");reference.setGeneric(true);GenericService genericService = reference.get();String result = genericService.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{"Kimi"});System.out.println(result);}
}
泛化調用不需要提前知道服務接口的具體定義。
通過以上步驟,可以實現一個完整的 Dubbo 服務調用案例