dubbo实战之三:使用Zookeeper注册中心

欢迎访问我的GitHub

https://github.com/zq2599/blog_demos

内容:所有原创文章分类汇总及配套源码,涉及Java、Docker、Kubernetes、DevOPS等;

《dubbo实战》系列导航

  1. 准备和初体验
  2. 与SpringBoot集成
  3. 使用Zookeeper注册中心
  4. 管理控制台dubbo-admin

本篇概览

  • 本文是《dubbo实战》系列的第三篇,主要内容是使用Zookeeper作为注册中心的实战;
  • 前面两篇的实战都是使用了广播模式,整个环境由服务提供者和服务消费者组成,这种简单形态只是为了方便学习,实际上多数情况都会部署注册中心,服务提供者在上面注册,服务消费者再从注册中心得到具体的服务信息;
  • 下面是个典型的提供者、消费者、注册中心的典型架构图:

在这里插入图片描述

  • 如下图所示,dubbo官方推荐的注册中心是Zookeeper

在这里插入图片描述

关于Zookeeper

  1. 本次使用了单节点Zookeeper,版本3.4.13,IP192.168.50.43,端口2181
  2. 关于Zookeeper的部署,我这边是通过docker快速部署的,参考文章《群晖DS218+部署kafka》
  • 如果您部署好了Zookeeper,接下来开始编写服务提供者和消费者的代码;

源码下载

  1. 如果您不想编码,可以在GitHub下载所有源码,地址和链接信息如下表所示:
名称链接备注
项目主页https://github.com/zq2599/blog_demos该项目在GitHub上的主页
git仓库地址(https)https://github.com/zq2599/blog_demos.git该项目源码的仓库地址,https协议
git仓库地址(ssh)git@github.com:zq2599/blog_demos.git该项目源码的仓库地址,ssh协议
  1. 这个git项目中有多个文件夹,本章的应用在dubbopractice文件夹下,如下图红框所示:

在这里插入图片描述
3. dubbopractice是父子结构的工程,本篇的代码在springbootzkproviderspringbootzkconsumer这两个子工程中,如下图:

在这里插入图片描述

编码(服务提供方)

  • 先创建提供服务的工程springbootmulticastprovider,一共要创建4个文件,创建顺序和功能如下表:
创建顺序文件名作用
1pom.xml工程的pom文件
2src/main/resources/application.yml配置文件
3DemoServiceImpl.java提供具体的服务
4SpringBootZKProviderApplication.java启动类
  • 完整的文件位置如下图:

在这里插入图片描述

  • 接下来逐个创建上述内容;
  1. 创建名为springbootmulticastprovider的子工程,pom.xml内容如下,要重点关注的是新增依赖dubbo-spring-boot-starter,这就是dubbo在SpringBoot环境的starter依赖,还有Zookeeper的依赖dubbo-dependencies-zookeeper
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>dubbopractice</artifactId>
        <groupId>com.bolingcavalry</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.bolingcavalry</groupId>
    <artifactId>springbootzkprovider</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>springbootzkprovider</name>
    <description>Demo project for dubbo service provider from Spring Boot</description>

    <!--不用spring-boot-starter-parent作为parent时的配置-->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.3.3.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.bolingcavalry</groupId>
            <artifactId>practiceinterface</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-dependencies-zookeeper</artifactId>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${springboot.version}</version>
            </plugin>
        </plugins>
    </build>
</project>
  1. 配置文件application.yml,要注意的是registry.address的值zookeeper://192.168.50.43:2181,这就是Zookeeper注册中心的配置:
dubbo:
  application:
    #application-name 本模块名字
    name: springboot-zk-provider
  registry:
    address: zookeeper://192.168.50.43:2181
  protocol:
    name: dubbo
    port: 20880
  1. 编写服务实现类DemoServiceImpl.java,注意@Service注解将当前类的实例作为远程服务对外暴露:
package com.bolingcavalry.springbootzkprovider;

import com.bolingcavalry.dubbopractice.service.DemoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.rpc.RpcContext;

@Slf4j
@Service
public class DemoServiceImpl implements DemoService {
    @Override
    public String sayHello(String name) {
        log.info("I'm springboot-zk-provider, Hello " + name + ", request from consumer: " + RpcContext.getContext().getRemoteAddress());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "I'm springboot-zk-provider, Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress();
    }
}
  1. 编写SpringBoot启动类SpringBootZKProviderApplication.java,注意要添加@EnableDubbo注解
package com.bolingcavalry.springbootzkprovider;

import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableDubbo
public class SpringBootZKProviderApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootZKProviderApplication.class, args);
    }
}
  1. 至此服务提供方编码完成,直接在IDEA上运行SpringBootZKProviderApplication类即可启动服务,启动成功后的日志输出如下图,如红框所示,已连上了Zookeeper:

在这里插入图片描述

编码(服务消费方)

  • 现在网络上已经有了服务,咱们再来编写服用消费方的代码,一共要创建6个文件,创建顺序和功能如下表:
创建顺序文件名作用
1pom.xml工程的pom文件
2src/main/resources/application.yml配置文件
3RemoteInvokeServiceImpl.javaservice层,在这里远程调用服务提供方的服务
4DemoController.javaweb接口类,对外提供web服务
5SwaggerConfig.javaswagger配置类,便于通过页面测试接口
6SpringBootZKConsumerApplication.java启动类
  • 完整的文件位置如下图:

在这里插入图片描述

  • 接下来逐个创建上述文件;
  1. 创建名为springbootzkconsumer的子工程,pom.xml内容如下,同样需要依赖dubbo-spring-boot-starterdubbo-dependencies-zookeeper
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>dubbopractice</artifactId>
        <groupId>com.bolingcavalry</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.bolingcavalry</groupId>
    <artifactId>springbootzkconsumer</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>springbootzkconsumer</name>
    <description>Demo project for dubbo service consumer from Spring Boot</description>

    <!--不用spring-boot-starter-parent作为parent时的配置-->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.3.3.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- swagger依赖 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
        </dependency>
        <!-- swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
        </dependency>
        <dependency>
            <groupId>com.bolingcavalry</groupId>
            <artifactId>practiceinterface</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-dependencies-zookeeper</artifactId>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${springboot.version}</version>
            </plugin>
        </plugins>
    </build>
</project>
  1. 编写配置文件application.yml,注意dubbo.registry.address的值:
dubbo:
  application:
    #application-name 本模块名字
    name: springboot-zk-consumer
  registry:
    address: zookeeper://192.168.50.43:2181
server:
  port: 8081
  1. 编写调用远程服务的代码,如下,可见如果想调用远程服务,只要对接口做@Reference注释即可,另外还通过timeout属性增加了超时配置:
package com.bolingcavalry.springbootzkconsumer.service;

import com.bolingcavalry.dubbopractice.service.DemoService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;

@Service
public class RemoteInvokeServiceImpl {

    @Reference(timeout = 2000)
    private DemoService demoService;

    public String sayHello(String name) {
        return "from dubbo remote (zk registry center mode) : " + demoService.sayHello(name);
    }
}
  1. 再编写对外提供web服务的Controller类:
package com.bolingcavalry.springbootzkconsumer.controller;

import com.bolingcavalry.springbootzkconsumer.service.RemoteInvokeServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/demo")
@Api(tags = {"DemoController"})
public class DemoController {
    @Autowired
    private RemoteInvokeServiceImpl remoteInvokeService;

    @ApiOperation(value = "获取dubbo service provider的响应", notes="\"获取dubbo service provider的响应")
    @ApiImplicitParam(name = "name", value = "昵称", paramType = "path", required = true, dataType = "String")
    @RequestMapping(value = "/{name}", method = RequestMethod.GET)
    public String sayHello(@PathVariable String name){
        return remoteInvokeService.sayHello(name);
    }
}
  1. 还要添加swagger配置类:
package com.bolingcavalry.springbootzkconsumer;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Tag;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .tags(new Tag("DemoController", "演示服务"))
                .select()
                // 当前包路径
                .apis(RequestHandlerSelectors.basePackage("com.bolingcavalry.springbootzkconsumer.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    //构建 api文档的详细信息函数,注意这里的注解引用的是哪个
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //页面标题
                .title("dubbo远程调用服务的操作(zk注册中心)")
                //创建人
                .contact(new Contact("程序员欣宸", "https://github.com/zq2599/blog_demos", "zq2599@gmail.com"))
                //版本号
                .version("1.0")
                //描述
                .description("API 描述")
                .build();
    }
}
  1. 最后是启动类SpringBootZKConsumerApplication.java
package com.bolingcavalry.springbootzkconsumer;

import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableDubbo
public class SpringBootZKConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootZKConsumerApplication.class, args);
    }
}
  1. 至此,服务消费方编码完成,直接在IDEA上运行SpringBootZKConsumerApplication类即可启动,如下图,可见服务消费方也连接Zookeeper成功:

在这里插入图片描述
8. 通过浏览器访问swagger,地址是:http://localhost:8081/swagger-ui.html ,如下图,点击红框位置展开接口详情:

在这里插入图片描述

  1. 如下图,输入web接口参数发起请求:

在这里插入图片描述
10. 下图红框中就是响应的数据,内容是springbootzkconsumer远程调用springbootzkprovider的服务得到的:

在这里插入图片描述

查看Zookeeper上的数据

  1. 再回顾一下官方的有关Zookeeper注册中心中数据的描述,如下图:

在这里插入图片描述

  1. 按照上述信息,咱们去Zookeeper看看数据,验证和上图是否一致,登录Zookeeper后执行zkCli.sh进度交互模式;
  2. 查看根目录,果然有名为dubbo的子目录:
[zk: localhost:2181(CONNECTED) 18] ls /                                                                    
[dubbo, log_dir_event_notification, isr_change_notification, zookeeper, admin, consumers, cluster, config, latest_producer_id_block, controller, brokers, controller_epoch]
  1. 再看dubbo目录下,有远程服务的子目录:
[zk: localhost:2181(CONNECTED) 19] ls /dubbo
[com.bolingcavalry.dubbopractice.service.DemoService, config, metadata]
  1. 查看远程服务的providers节点,果然有服务提供者的信息:
[zk: localhost:2181(CONNECTED) 16] get /dubbo/com.bolingcavalry.dubbopractice.service.DemoService/providers
169.254.38.208
cZxid = 0x552
ctime = Sat Oct 17 04:05:52 UTC 2020
mZxid = 0x552
mtime = Sat Oct 17 04:05:52 UTC 2020
pZxid = 0x5ec
cversion = 27
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 14
numChildren = 1
  1. 再看看consumer节点的内容:
[zk: localhost:2181(CONNECTED) 17] get /dubbo/com.bolingcavalry.dubbopractice.service.DemoService/consumers
169.254.38.208
cZxid = 0x55f
ctime = Sat Oct 17 04:22:58 UTC 2020
mZxid = 0x55f
mtime = Sat Oct 17 04:22:58 UTC 2020
pZxid = 0x5f0
cversion = 33
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 14
numChildren = 1
  1. 可见Zookeeper上记录的数据与官方文档描述的一致;
  • 至此,dubbo与springboot集成的实战就完成了,希望能给您提供一些参考,助您快速开发dubbo应用;

欢迎关注公众号:程序员欣宸

微信搜索「程序员欣宸」,我是欣宸,期待与您一同畅游Java世界...

你不孤单,欣宸原创一路相伴

  1. Java系列
  2. Spring系列
  3. Docker系列
  4. kubernetes系列
  5. 数据库+中间件系列
  6. DevOps系列

欢迎关注公众号:程序员欣宸

微信搜索「程序员欣宸」,我是欣宸,期待与您一同畅游Java世界...
https://github.com/zq2599/blog_demos

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值