Skip to main content

Dubbo RPC

Dubbo RPC 是阿里最先开发,现在属于 Apache 的 RPC 框架。Dubbo RPC 默认使用 gRPC 协议,但也支持其它通信协议。同时 Dubbo RPC 还能与之前我们在 k8s 介绍的 istio 服务网格集成。其使用比起直接的 gRPC 更方便。

如果你喜欢用 Spring Initializr,Dubbo 也提供了自己的 initializer。但是作者更偏好手动引库。注意不用引 Spring Boot Web,只引 Spring Framework 的 Spring Boot 即可。

依赖配置

注意要退一下版本,目前 Dubbo 3.3 配的是 SpringBoot 3.1.2。

plugins {
id 'java'
id 'org.springframework.boot' version '3.1.2'
}

allprojects {
ext {
set("springBootVersion", "3.1.2")
set('dubboVersion', '3.3.0')
}

repositories {
mavenCentral()
}

apply {
plugin 'java'
plugin 'org.springframework.boot'
}

dependencies {
implementation platform("org.apache.dubbo:dubbo-bom:${dubboVersion}")
implementation "org.springframework.boot:spring-boot-starter:${springBootVersion}"
implementation 'org.apache.dubbo:dubbo-spring-boot-starter'
implementation 'org.apache.dubbo:dubbo-nacos-spring-boot-starter'
}

java {
sourceCompatibility = JavaLanguageVersion.of(21)
targetCompatibility = JavaLanguageVersion.of(21)
}

group = 'com.github.fingerbone'
version = '1.0-SNAPSHOT'
}

这里我们注册到 NacOS 里,也可以使用别的注册中心,但是 NacOS 支持最好(同一家的毕竟),我们用 docker 再起一个 NacOS,和之前一样。配置一下就好。

spring:
application:
name: dubbo-server
dubbo:
registry:
address: nacos://localhost:8848

注意这里一定要写名字。

服务实现

用 Dubbo 写 RPC 会方便很多,写一个接口然后实现即可,不需要手动写 proto 文件。

public interface DemoService {
String sayHello(String name);
}

@DubboService
public class DemoServiceImpl implements DemoService {
@Override
public String sayHello(String name) {
return "Hello " + name;
}
}

注意启动类还要额外加 @EnableDubbo。启动后,NacOS 里可以看到服务。

实际写的时候,应该把接口单独放一个项目里,以简化依赖关系。

服务调用

再开一个子项目,

dependencies {
implementation "org.springframework.boot:spring-boot-starter-web:${springBootVersion}"
implementation project(':server')
}

子项目要调用 Dubbo 微服务,也要写上 @EnableDubbo

要调用只需要,

package com.github.fingerbone;

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {
@DubboReference
private DemoService demoService;

@GetMapping
public String hello(String name) {
return demoService.hello(name);
}
}

然后换一下端口,

spring:
application:
name: dubbo-client
server:
port: 8088
dubbo:
application:
qos-port: 33333
registry:
address: nacos://localhost:8848
protocol:
port: 30880