1. 程式人生 > 其它 >Springboot整合Dubbo系列二:已有專案整合Dubbo

Springboot整合Dubbo系列二:已有專案整合Dubbo

技術標籤:Dubbo分散式Zookeeperspring bootzookeeperdubbo

0.版本

已有專案的Springboot版本:2.2.6.RELEASE

Dubbo版本:maven配置是0.2.0,原始碼版本是2.6.2

1.Maven整合已有或新建專案

將多個專案整合成功一個專案多模組,多模組直接需要互相呼叫,所以都是平級的,既是生產者也是消費者

2.新增依賴

因為各模組已在pom配置了parent為主專案,所以再主專案的pom新增相關依賴即可

<properties>		
	<curator-framework.version>4.0.1</curator-framework.version
>
<zookeeper.version>3.4.13</zookeeper.version> <dubbo.starter.version>0.2.0</dubbo.starter.version> </properties> <dependency> <groupId>com.alibaba.boot</groupId> <artifactId>dubbo-spring-boot-starter</artifactId> <version>
${dubbo.starter.version}</version> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-framework</artifactId> <version>${curator-framework.version}</version> </dependency> <dependency> <
groupId
>
org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>${zookeeper.version}</version> </dependency>

3.yml配置

dubbo:
  application:
    name: 應用名
  protocol:
    name: dubbo
# port埠每個專案配成不一樣的
    port: 20880
  registry:
    address: zookeeper://zk的IP:2181
  provider:
    timeout: 1000
# 如果多專案互為生產者消費者,此項需設為false,不然啟動時會檢查生產者是否啟動,先啟動的消費者就連不上後啟動的生產者
  consumer:
    check: false
# 自定義dubbo version,用於區分service版本
dv:
  service:
    version: 1.0.0

4.註解

在啟動類添加註解

@EnableDubbo

在這裡插入圖片描述

5.新建公共介面專案

新建一個專案,定義兩系統需要互動的介面,我就叫它對外Service吧

在這裡插入圖片描述

介面內容如下,就一個簡單的介面

public interface DwService {
    String hello(String name);
}

6.生產者者實現類

1.此@Service要用dubbo的,version取了yml中的配置

2.實現類繼承公共介面,將介面方法實現

import com.alibaba.dubbo.config.annotation.Service;
import com.***.***api.service.DwService;

@Service(version = "${dv.service.version}")
public class ***DwServiceImpl implements DwService {

    @Override
    public String hello(String name) {
        return "I'm provider ,hello, " + name;
    }
}

7.消費者呼叫類

在消費者端實現呼叫

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.***.***api.service.DwService;

@RestController
public class ***DwController {

    @Reference(version = "${dv.service.version}")
    private DwService dwService;

    @RequestMapping("/hello/{name}")
    public String zwcxHello(@PathVariable("name") String name) {
        return dwService.hello(name);
    }
}

8.測試

啟動兩個專案,在生產者頁面,修改瀏覽器位址列url

http://127.0.0.1:8888/應用名稱/hello/生產者

在這裡插入圖片描述