dubbo通过zookeeper注册服务

1050
2024/12/26 18:31:31
栏目: 大数据
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

Dubbo 是一个高性能、轻量级的开源 Java RPC 框架,它支持通过 Zookeeper 进行服务注册和发现。下面是一个简单的步骤来演示如何使用 Dubbo 和 Zookeeper 进行服务注册:

  1. 添加依赖

首先,在你的项目中添加 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>
  1. 配置 Dubbo

在项目的 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
  1. 创建服务接口和实现类

创建一个名为 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;
    }
}
  1. 启用 Dubbo 自动扫描

在你的 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);
    }
}
  1. 启动 Zookeeper 服务器

确保你的 Zookeeper 服务器已经启动并运行在 127.0.0.1:2181 地址上。如果没有,请参考 Zookeeper 官方文档 启动一个 Zookeeper 实例。

  1. 测试服务注册和发现

现在你可以启动 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” 的响应。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: dubbo和zookeeper版本兼容吗