Spring Cloud Alibaba基礎教程第二篇:消費方式

在上一篇Spring Cloud Alibaba基礎教程第一篇:使用Nacos實現服務註冊與發現 文章的學習,咱們演示Nacos來實現服務的註冊與發現,同時也介紹如何經過LoadBalancerClient接口來獲取某個服務的具體實例,並根據實例信息來發起服務接口消費請求。經過代碼能夠看到要手動添加服務以及進行URL連接拼接比較麻煩的,有學過Spring Cloud的朋友應該知道兩種調用方式,Ribbon和Feign,因此接下來,咱們來演示下這樣的服務消費方式java

SpringCloud版本整合Eureka時能夠很好的經過結合Ribbon + RestTemplate實例來共同完成服務調用的負載均衡,固然Nacos Discovery一樣能夠無縫的對接Ribbon來完成LoadBalance請求健康的服務地址。git

Nacos Discovery內部默認集成了Ribbon,集成的方式跟Eureka幾乎一致。github

沒接觸過二者的能夠先看下Spring Cloud教程web

一. 使用Ribbon+RestTemplate

建立消費者應用

按照上一篇的項目進行建立命名爲resttemplate-serverspring

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>
    <parent>
        <groupId>com.xd</groupId>
        <artifactId>SpringCloudAlibabaLearn</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../</relativePath>
    </parent>
    <artifactId>alibaba-nacos-resttemplate-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>alibaba-nacos-resttemplate-server</name>
    <description>RestTemplate調用服務</description>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
複製代碼
application.yml

application.properties配置文件內相關的信息,以下所示:apache

server.port=8082
#resttemplate消費者
spring.application.name=resttemplate-server
#註冊服務到nacos
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
複製代碼
建立請求類,並實現一個接口

主要使用ResteTemplate來調用服務,在入口類內添加以下代碼:瀏覽器

package com.xd.alibabanacosresttemplateserver;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * ribbon方式消費請求路徑
 */
@RestController
@EnableDiscoveryClient
@SpringBootApplication
public class AlibabaNacosResttemplateServerApplication {

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

    /**
     * 使用RestTemplate
     * 兩種調用方法 一種是服務id(要開啓負載均衡)一個是域名(不用開啓負載均衡)
     * 實例化RestTemplate
     *@LoadBalanaced 這個註解對於學過SpringCloud的朋友是熟悉的,該註解開啓RestTemplate使用Ribbon來作負載均衡
     * @return
     */
    @Bean
//    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Autowired
    private RestTemplate restTemplate;



    @GetMapping("/testOne")
    public String testOne() {
        // 使用域名時 將@LoadBalanced註解註釋 -> 本身實現 ip:端口號/調用鏈接
        String result = restTemplate.getForObject("http://localhost:8080/echo/lhd", String.class);
        return "Return : " + result;
    }


    /**
     * 咱們在調用服務時是經過服務名的方式來進行指定路徑請求
     * Ribbon會自動根據provider-service服務名去Nacos Server拉取全部健康的服務列表
     * 根據負載的策略來獲取一個具體服務的ip + port再進行訪問
     * @return
     */
    @GetMapping("/testTwo")
    public String testTwo() {
        // 使用負載均衡
        String result = restTemplate.getForObject("http://provider-service/echo/lhd", String.class);
        return "Return : " + result;
    }

}
複製代碼

上面👆主要講述: 在微服務的使用中若是使用RestTemplate來進行rpc遠程調用的時候 ,在調用會員服務的時候有的會選擇使用會員服務端在註冊中心註冊的名稱來進行遠程調用 也有的會直接使用域名(ip:port)進行調用,在這個過程當中若是使用會員的註冊名稱的話在RestTemplate 那裏開啓 負載均衡 : @LoadBalanced若是是使用域名進行調用就不用開啓負載均衡bash

運行測試

第一步:啓動alibaba-nacos-provider-server服務app

沒有的能夠下載啓動便可負載均衡

第二步:啓動本章alibaba-nacos-resttemplate-server服務

第三步:訪問測試

打開瀏覽器訪問: http://localhost:8082/testOne 或者 http://localhost:8082/testTwo

查看返回內容以下所示:

打開@LoadBalanced進行服務時,會自動進行負載,獲取可用的服務地址,控制檯日誌信息以下:

二. 使用Feign

建立消費者應用

按照上一篇的項目進行建立命名爲resttemplate-server 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>
    <parent>
        <groupId>com.xd</groupId>
        <artifactId>SpringCloudAlibabaLearn</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../</relativePath>
    </parent>
    <artifactId>alibaba-nacos-feign-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>alibaba-nacos-feign-server</name>
    <description>Feign消費調用</description>

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

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
複製代碼
application.yml

application.properties配置文件內相關的信息,以下所示:

server.port=8083
#feign消費者
spring.application.name=feign-server
#註冊服務到nacos
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
複製代碼
建立請求類,並實現一個接口

主要使用ResteTemplate來調用服務,在入口類內添加以下代碼:

package com.xd.alibabanacosfeignserver;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;


@EnableFeignClients // 開啓feign調用
@RestController
@EnableDiscoveryClient
@SpringBootApplication
public class AlibabaNacosFeignServerApplication {

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

    /**
     * 使用@FeignClient註解來指定這個接口所要調用的服務名稱
     */
    @FeignClient("provider-service")
    interface Client {
        @GetMapping("/echo/{name}")
        String hello(@PathVariable(name = "name") String name);
    }

    // 定義feign客戶端
    @Autowired
    private Client client;


    // 調用
    @GetMapping("/test")
    public String test() {
        String result = client.hello("lhd");
        return "Return : " + result;
    }
}
複製代碼

這裏主要描述: 經過@EnableFeignClients註解開啓掃描Spring Cloud Feign客戶端的功能;而後又建立一個Feign的客戶端接口定義。使用@FeignClient註解來指定這個接口所要調用的服務名稱,下面就是綁定provider-service服務的/echo/{name}接口的例子。最後,在Controller中,注入了Client接口的實現,並調用test方法來觸發對服務提供方的調用

運行測試

第一步:啓動alibaba-nacos-provider-server服務

沒有的能夠下載啓動便可

第二步:啓動本章alibaba-nacos-resttemplate-server服務

第三步:訪問測試

打開瀏覽器訪問: http://localhost:8083/test

查看返回內容以下所示:

查看控制檯發現,一樣進行了負載均衡,由於Feign封裝了Ribbon, Feign是在Ribbon的基礎上進行了一次改進,採用接口的方式,將須要調用的其餘服務的方法定義成抽象方法就好了

四. 參考資料:

五. 代碼示例

若是您對這些感興趣,歡迎star、follow、收藏、轉發給予支持!

相關文章
相關標籤/搜索