1. 程式人生 > 其它 >【Dubbo】構建SpringBoot整合Dubbo的Demo

【Dubbo】構建SpringBoot整合Dubbo的Demo

參考樂位元組的Dubbo教程

https://www.bilibili.com/video/BV19L4y1n7YE

Zookeeper單機部署 (Windows)

因為專案需要,這裡我自己學習就採用Zookeeper作為註冊中心

ZK的穩定版本映象倉庫

https://downloads.apache.org/zookeeper/stable/

下載後解壓出來,拷貝一份zoo_sample.cfg重新命名為zoo.cfg

配置資訊:

主要是這三個資訊需要根據自己需要變更

# The number of milliseconds of each tick
tickTime=2000
# The number of ticks that the initial 
# synchronization phase can take
initLimit
=10 # The number of ticks that can pass between # sending a request and getting an acknowledgement syncLimit=5 # the directory where the snapshot is stored. # do not use /tmp for storage, /tmp here is just # example sakes. dataDir=E:\\apache-zookeeper-3.7.0-bin\\data zk的資料輸出目錄 # the port at which the clients will connect clientPort
=2181 zk的預設客戶埠2181 admin.serverPort=2180 這個是zk的服務埠配置,預設8080 # the maximum number of client connections. # increase this if you need to handle more clients #maxClientCnxns=60 # # Be sure to read the maintenance section of the # administrator guide before turning on autopurge. # # http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance # # The number of snapshots to retain in dataDir #autopurge.snapRetainCount
=3 # Purge task interval in hours # Set to "0" to disable auto purge feature #autopurge.purgeInterval=1 ## Metrics Providers # # https://prometheus.io Metrics Exporter #metricsProvider.className=org.apache.zookeeper.metrics.prometheus.PrometheusMetricsProvider #metricsProvider.httpPort=7000 #metricsProvider.exportJvmInfo=true

然後雙擊cmd指令碼啟動

zkServer.cmd

Linux則是shell指令碼,需要加上引數

zkServer.sh start

只要終端視窗沒有 [ERROR]就表示ZK執行正常

Linux使用命令檢視

zkServer.sh status

Demo工程結構:

新建一個Maven工程,把原始碼目錄刪除後,配置Pom檔案

<?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">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.cloud9</groupId>
    <artifactId>Dubbo-Sample</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <!-- 管理的模組 -->
    <modules>
        <module>Common-API</module>
        <module>Provider</module>
        <module>Consumer</module>
    </modules>

    <!-- 配置dubbo的版本 -->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <java.version>1.8</java.version>
        <dubbo.version>2.0.0</dubbo.version>
    </properties>

    <parent>
        <!-- 指定Springboot版本 -->
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
    </parent>

    <!-- 管理依賴的版本,不是用來匯入的 -->
    <dependencyManagement>
        <dependencies>
            <!-- dubbo-starter 元件 -->
            <dependency>
                <groupId>com.alibaba.spring.boot</groupId>
                <artifactId>dubbo-spring-boot-starter</artifactId>
                <version>${dubbo.version}</version>
            </dependency>

            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.22</version>
            </dependency>

            <!-- dubbo使用zk作為註冊中心需要的依賴元件 -->
            <dependency>
                <groupId>org.apache.dubbo</groupId>
                <artifactId>dubbo-dependencies-zookeeper</artifactId>
                <version>2.7.8</version>
                <type>pom</type>
            </dependency>

            <!-- 上面zk元件沒有客戶端,還需要單獨引入 -->
            <dependency>
                <groupId>com.101tec</groupId>
                <artifactId>zkclient</artifactId>
                <version>0.9</version>
            </dependency>

        </dependencies>
    </dependencyManagement>

</project>

Common-API包

也是普通Maven專案

這個裡面只需要提供公共的PO和呼叫介面即可

所有通用的依賴元件都在這個包裡面引入

沒有任何Spring的配置資訊

商品PO類

package cn.cloud9.common.pojo;
import lombok.*;
import java.io.Serializable;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@EqualsAndHashCode
public class Goods implements Serializable {
    private String id;
    private String name;
    private Integer count;
}

呼叫的介面規範

package cn.cloud9.common.service;
import cn.cloud9.common.pojo.Goods;
import java.util.List;

public interface ProviderService {
    List<Goods> listEnableGoods();
}

common-api注入的依賴:

<?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>Dubbo-Sample</artifactId>
        <groupId>cn.cloud9</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>Common-API</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.spring.boot</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-dependencies-zookeeper</artifactId>
            <type>pom</type>
        </dependency>

        <!-- https://blog.csdn.net/pri_sta_pub/article/details/79087592 -->
        <dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

</project>

Provider 生產者服務

生產者將規定的介面進行實現

注意這裡打註解,按照DEMO演示只需要打上Dubbo的@Service就可以了

實際情況可能Spring也會需要,因為生產者服務自己也可能是一個web服務

這裡把完整資源名稱寫出來

package cn.cloud9.provider.service;

import cn.cloud9.common.service.ProviderService;
import cn.cloud9.common.pojo.Goods;
import java.util.ArrayList;
import java.util.List;

@com.alibaba.dubbo.config.annotation.Service(interfaceClass = ProviderService.class)
@org.springframework.stereotype.Service
public class ProviderServiceImpl implements ProviderService {

    @Override
    public List<Goods> listEnableGoods() {
        List<Goods> goodsList = new ArrayList<>();
        Goods goods = null;
        for (int i = 0; i < 10; i++) {
            goods = new Goods("GOODS-1001-ZXC-" + i, "GOODS-NAME-" + i, 10);
            goodsList.add(goods);
        }
        return goodsList;
    }
}

然後是啟動類

除了Springboot啟動類,還需要Dubbo配置註解

注意其他需要掃描的類,都需要和啟動類同包內

package cn.cloud9.provider;

import com.alibaba.dubbo.spring.boot.annotation.EnableDubboConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@EnableDubboConfiguration
@SpringBootApplication
public class ProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(ProviderApplication.class, args);
    }
}

生產者的dubbo配置資訊:

server:
  port: 8081

spring:
  application: 
    name: dubbo-provider # 服務名稱
  dubbo: # dubbo配置
    server: true
    application: 
      name:  provider # dubbo註冊的名稱
    registry: # 註冊中心地址和埠
      address: zookeeper://localhost:2181
    protocol: # 採用的協議和埠
      name: dubbo
      port: 20880
    scan: cn.cloud9.provider.service # 掃描的資源地址

生產者引入的依賴只需要Common-API一個就滿足了

<?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>Dubbo-Sample</artifactId>
        <groupId>cn.cloud9</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>Provider</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>cn.cloud9</groupId>
            <artifactId>Common-API</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>

Consumer 消費者服務

消費者和生產者一樣都是隻需要引入Common-API

消費只需要注入介面引用,呼叫即可

注意,需要使用Dubbo提供的@Reference註解注入

package cn.cloud9.consumer.controller;

import cn.cloud9.common.service.ProviderService;
import cn.cloud9.common.pojo.Goods;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/consume")
public class ConsumerController {

    @Reference(interfaceClass = ProviderService.class)
    private ProviderService providerService;

    /**
     * /consume/goods
     * @return
     */
    @GetMapping("/goods")
    public String getEnableGoodsList() {
        final List<Goods> goodsList = providerService.listEnableGoods();
        return goodsList.toString();
    }
}

消費者的啟動類和生產者一樣,需要配置@DubboConfiguration

package cn.cloud9.consumer;

import com.alibaba.dubbo.spring.boot.annotation.EnableDubboConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@EnableDubboConfiguration
@SpringBootApplication
public class ConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }
}

然後是消費者的配置資訊,和生產者區分開來

1、服務不能和生產者一個埠號

2、服務名稱

3、dubbo註冊的服務名稱

4、掃描的包

server:
  port: 8083

spring:
  application:
    name: dubbo-consumer
  dubbo:
    server: true
    application:
      name:  consumer
    registry:
      address: zookeeper://localhost:2181
    protocol:
      name: dubbo
      port: 20880
    scan: cn.cloud9.consumer

呼叫執行測試

上述步驟配置完成後

使用介面測試工具或者瀏覽器訪問我們提供的web介面

localhost:8083/consume/goods

如果響應了資料,則呼叫正常

[Goods(id=GOODS-1001-ZXC-0, name=GOODS-NAME-0, count=10), Goods(id=GOODS-1001-ZXC-1, name=GOODS-NAME-1, count=10), Goods(id=GOODS-1001-ZXC-2, name=GOODS-NAME-2, count=10), Goods(id=GOODS-1001-ZXC-3, name=GOODS-NAME-3, count=10), Goods(id=GOODS-1001-ZXC-4, name=GOODS-NAME-4, count=10), Goods(id=GOODS-1001-ZXC-5, name=GOODS-NAME-5, count=10), Goods(id=GOODS-1001-ZXC-6, name=GOODS-NAME-6, count=10), Goods(id=GOODS-1001-ZXC-7, name=GOODS-NAME-7, count=10), Goods(id=GOODS-1001-ZXC-8, name=GOODS-NAME-8, count=10), Goods(id=GOODS-1001-ZXC-9, name=GOODS-NAME-9, count=10)]