【微服務】Nacos實現服務間的調用 后端程序猿必經之路



在這里插入圖片描述

前言

之前的文章講訴了Nacos的具體功能,那么有了理論肯定是不夠的,這一次我們來利用Nacos實現簡單的服務之間簡單的調用,對於Nacos不是很了解可以先去看看 【微服務】 Nacos的入門級使用 后端程序猿必經之路
話不多說,開整開整
在這里插入圖片描述

工具

IDEA,Nacos客戶端(linux和windows都可以,這里以windows作為講解)

開發流程

Nacos客戶端的啟動

來到Nacos的解壓目錄下,來到bin目錄,雙擊startup.cmd即可
在這里插入圖片描述
如下圖,則啟動成功
在這里插入圖片描述

代碼編寫

建立一個maven項目

建立項目

直接使用Idea建立一個maven項目即可,src之類的文件夾不需要留下,只留一個pom.xml即可,如下圖所示,只留下紅色箭頭所指內容即可,其他全部刪除。該maven項目作為總項目,作用就是方便各個子模塊之間的依賴版本統一。
在這里插入圖片描述

pom.xml內容

<?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>com.xiaow</groupId>
    <artifactId>test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>dependcies</module>
        <module>provider</module>
        <module>consumer</module>
    </modules>
    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.2.5.RELEASE</spring-boot.version>
    </properties>
    <packaging>pom</packaging>


    <profiles>
        <profile>
            <!-- 開發環境 -->
            <id>dev</id>
            <properties>
                <env>dev</env>
            </properties>
            <activation>
                <!-- 默認激活該profile節點-->
                <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <resources>
                    <resource>
                        <directory>src/main/resources_env/dev</directory>
                    </resource>
                    <resource>
                        <directory>src/main/resources</directory>
                    </resource>
                </resources>
            </build>
        </profile>
        <profile>
            <!-- 測試環境 -->
            <id>qa</id>
            <properties>
                <env>qa</env>
            </properties>
            <build>
                <resources>
                    <resource>
                        <directory>src/main/resources_env/qa</directory>
                    </resource>
                    <resource>
                        <directory>src/main/resources</directory>
                    </resource>
                </resources>
            </build>
        </profile>
        <profile>
            <!-- 生產環境 -->
            <id>online</id>
            <properties>
                <env>online</env>
            </properties>
            <build>
                <resources>
                    <resource>
                        <directory>src/main/resources_env/online</directory>
                    </resource>
                    <resource>
                        <directory>src/main/resources</directory>
                    </resource>
                </resources>
            </build>
        </profile>
    </profiles>
    
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.xiaow</groupId>
                <artifactId>dependcies</artifactId>
                <version>${project.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

<!--maven倉庫的配置-->
    <repositories>
        <repository>
            <id>aliyun-repos</id>
            <name>Aliyun Repository</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>

        <repository>
            <id>sonatype-repos</id>
            <name>Sonatype Repository</name>
            <url>https://oss.sonatype.org/content/groups/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>sonatype-repos-s</id>
            <name>Sonatype Repository</name>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>

        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

建立統一的依賴管理模塊

這個模塊的作用其實就是使得總項目的pom.xml看着整潔一點,並且實現整個項目的依賴管理
也是一樣,建立一個maven的module,只留一個pom.xml即可
內容如下

<?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">
    <groupId>com.xiaow</groupId>
    <version>1.0-SNAPSHOT</version>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>dependcies</artifactId>
    <packaging>pom</packaging>

    <properties>
        <spring-cloud-version>Hoxton.SR4</spring-cloud-version>
        <spring-cloud-alibaba-version>2.2.2.RELEASE</spring-cloud-alibaba-version>
    </properties>
    <developers>
        <developer>
            <id>1</id>
            <name>xiaow</name>
        </developer>
    </developers>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud-version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba-version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
                <version>0.9.0.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-alibaba-nacos-config</artifactId>
                <version>0.9.0.RELEASE</version>
            </dependency>

            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
                <version>0.9.0.RELEASE</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <repositories>
        <repository>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
            <layout>default</layout>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>

在主項目的pom.xml中需要在dependencyManagement中將其引入,如下圖所示
在這里插入圖片描述
到現在為止,我么已經完成了整個環境的搭建。

生產者服務

生產者服務,顧名思義,該服務的作用就是供消費者服務進行消費的,那么類比到服務之間的關系應該叫做調用。

建立一個maven模塊

建立一個maven模塊,這一次要留下src這個文件夾。

pom.xml

<?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>test</artifactId>
        <groupId>com.xiaow</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>provider</artifactId>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <!--	<dependencies>-->
    <!-- 配置依賴關系 -->
    <dependencies>
        <!-- web啟動器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--        </dependencies>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.xiaow.test.Provider8001</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

建立接口供消費者服務調用

這里只是簡單寫了一個接口,返回一個字符串

package com.xiaow.test.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @GetMapping("/test")
    public String test() {
        return "調用成功";
    }
}

啟動類配置

在啟動類上加上@EnableDiscoveryClient注解。如下圖所示,這里要注意,建立的maven項目是沒有啟動類的,是需要我們自己手寫的或則復制。
在這里插入圖片描述

application.yml

這里要配置我們要注冊的nacos的地址

spring:
  application:
    name: provider
  cloud:
    nacos:
      discovery:
        server-addr: http://192.168.30.1:8848/
server:
  port: 8001

management:
  endpoints:
    web:
      exposure:
        include: "*"

最終項目結構

在這里插入圖片描述

測試是否成功

啟動一下該生產者是否成功注冊到Nacos,來到Nacos的工作台,如下圖所示
在這里插入圖片描述
觀察到provider已經注冊進來,說明生產者服務已經成功寫好。

消費者服務

和生產者一樣需要建立一個maven的Moudule,這里就不贅述了,我們本次消費者調用生產者服務的方式是openfegin方式。

pom.xml

消費者和生產者的pom文件有一些小小的不同,主要就是在openfegin這里

<?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>test</artifactId>
        <groupId>com.xiaow</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

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

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.xiaow.consumer.Consumer9001</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>


</project>

application.yml

spring:
  application:
    name: consumer
  cloud:
    nacos:
      discovery:
        server-addr: http://192.168.30.1:8848/
server:
  port: 9001

management:
  endpoints:
    web:
      exposure:
        include: "*"

啟動類的配置

需要加入@EnableDiscoveryClient,@EnableFeignClients這兩個注解

package com.xiaow.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class Consumer9001 {
    public static void main(String[] args) {
        SpringApplication.run(Consumer9001.class,args);
    }
}

調用生產者服務接口的service

這里的service就是可以直接調用生產者的接口,其中@GetMapping("/test")中的/test要與生產者接口的mapping相對應。

package com.xiaow.consumer.service;

import com.xiaow.consumer.service.impl.TestServiceImpl;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(name = "provider",fallback = TestServiceImpl.class)
public interface TestSerice {
    @GetMapping("/test")
    public String test();

}

TestServiceImpl實在調用生產者接口出現錯誤時才會被調用,具體使用等以后整合sentinel時在仔細說一下。

package com.xiaow.consumer.service.impl;

import com.xiaow.consumer.service.TestSerice;

public class TestServiceImpl implements TestSerice {
    @Override
    public String test() {
        return null;
    }
}

消費者接口

使用controller來調用TestService,從而實現對生產者服務的調用

package com.xiaow.consumer.controller;

import com.xiaow.consumer.service.TestSerice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @Autowired
    TestSerice testSerice;

    @GetMapping("/consumertest")
    public String consumertest() {
        return testSerice.test();
    }
}

測試

在這里插入圖片描述
成功調用,到此,一個基本的nacos使用就完成了

總結

目錄些許有些亂,大家有什么問題可以隨時交流,歡迎各位大佬指點。
整個完整項目已上傳碼雲 有興趣的可以看一下
碼雲地址
在這里插入圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM