Dubbo 是一個高性能、輕量級的開源 Java RPC 框架,它支持通過 Zookeeper 進行服務注冊和發現。下面是一個簡單的步驟來演示如何使用 Dubbo 和 Zookeeper 進行服務注冊:
首先,在你的項目中添加 Dubbo 和 Zookeeper 的依賴。以 Maven 為例:
<dependencies>
<!-- Dubbo -->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
<version>2.7.8</version>
</dependency>
<!-- Zookeeper -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.13</version>
</dependency>
</dependencies>
在項目的 resources
目錄下創建一個名為 dubbo.properties
的文件,并添加以下內容:
# Zookeeper 注冊中心地址
dubbo.registry.address=zookeeper://127.0.0.1:2181
# 服務提供者和消費者的相關配置
dubbo.application.name=dubbo-provider
dubbo.registry.register=true
dubbo.registry.async=false
dubbo.protocol.name=dubbo
dubbo.protocol.port=20880
dubbo.scan.base-packages=com.example.provider
創建一個名為 HelloService
的接口,并添加一個方法 sayHello
:
public interface HelloService {
String sayHello(String name);
}
然后創建一個實現類 HelloServiceImpl
:
import org.apache.dubbo.config.annotation.Service;
import org.springframework.stereotype.Component;
@Service
@Component
public class HelloServiceImpl implements HelloService {
@Override
public String sayHello(String name) {
return "Hello, " + name;
}
}
在你的 Spring Boot 主類上添加 @EnableDubbo
注解,以啟用 Dubbo 的自動掃描功能:
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableDubbo
public class DubboProviderApplication {
public static void main(String[] args) {
SpringApplication.run(DubboProviderApplication.class, args);
}
}
確保你的 Zookeeper 服務器已經啟動并運行在 127.0.0.1:2181
地址上。如果沒有,請參考 Zookeeper 官方文檔 啟動一個 Zookeeper 實例。
現在你可以啟動 Dubbo 服務提供者,它會自動將服務注冊到 Zookeeper。然后你可以創建一個 Dubbo 服務消費者來調用這個服務。以下是一個簡單的消費者示例:
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Reference
private HelloService helloService;
@GetMapping("/hello")
public String hello(String name) {
return helloService.sayHello(name);
}
}
啟動服務消費者后,你可以通過訪問 /hello?name=yourName
來調用服務提供者的 sayHello
方法。如果一切正常,你應該會看到類似 “Hello, yourName” 的響應。