Spring Cloud 系列之 Feign 聲明式服務(wù)調(diào)用(一)

什么是 Feign

Feign 是 Spring Cloud Netflix 組件中的一個(gè)輕量級 RESTful 的 HTTP 服務(wù)客戶端,實(shí)現(xiàn)了負(fù)載均衡和 Rest 調(diào)用的開源框架,封裝了 Ribbon 和 RestTemplate,實(shí)現(xiàn)了 WebService 的面向接口編程,進(jìn)一步降低了項(xiàng)目的耦合度。

Feign 內(nèi)置了 Ribbon,用來做客戶端負(fù)載均衡調(diào)用服務(wù)注冊中心的服務(wù)。

Feign 本身并不支持 Spring MVC 的注解,它有一套自己的注解,為了更方便的使用,Spring Cloud 孵化了 OpenFeign。

Feign 是一種聲明式、模板化的 HTTP 客戶端(僅在 Consumer 中使用)。

Feign 支持的注解和用法請參考官方文檔:https://github.com/OpenFeign/feignspring.io 官網(wǎng)文檔

Feign 的使用方式是:使用 Feign 的注解定義接口,調(diào)用這個(gè)接口,就可以調(diào)用服務(wù)注冊中心的服務(wù)。

Feign 解決什么問題

Feign 旨在使編寫 JAVA HTTP 客戶端變得更加容易,F(xiàn)eign 簡化了 RestTemplate 代碼,實(shí)現(xiàn)了 Ribbon 負(fù)載均衡,使代碼變得更加簡潔,也少了客戶端調(diào)用的代碼,使用 Feign 實(shí)現(xiàn)負(fù)載均衡是首選方案。只需要你創(chuàng)建一個(gè)接口,然后在上面添加注解即可。

Feign 是聲明式服務(wù)調(diào)用組件,其核心就是:像調(diào)用本地方法一樣調(diào)用遠(yuǎn)程方法,無感知遠(yuǎn)程 HTTP 請求。

  • 它解決了讓開發(fā)者調(diào)用遠(yuǎn)程接口就跟調(diào)用本地方法一樣的體驗(yàn),開發(fā)者完全感知不到這是遠(yuǎn)程方法,更感知不到這是個(gè) HTTP 請求。無需關(guān)注與遠(yuǎn)程的交互細(xì)節(jié),更無需關(guān)注分布式環(huán)境開發(fā)。

  • 它像 Dubbo 一樣,Consumer 直接調(diào)用 Provider 接口方法,而不需要通過常規(guī)的 Http Client 構(gòu)造請求再解析返回?cái)?shù)據(jù)。

Feign vs OpenFeign

OpenFeign 是 Spring Cloud 在 Feign 的基礎(chǔ)上支持了 Spring MVC 的注解,如 @RequesMapping、@Pathvariable 等等。

OpenFeign 的 @FeignClient 可以解析 SpringMVC 的 @RequestMapping 注解下的接口,并通過動態(tài)代理的方式產(chǎn)生實(shí)現(xiàn)類,實(shí)現(xiàn)類中做負(fù)載均衡并調(diào)用服務(wù)。

Feign 入門案例

點(diǎn)擊鏈接觀看:Feign 入門案例視頻(獲取更多請關(guān)注公眾號「哈嘍沃德先生」)

feign-demo 聚合工程。SpringBoot 2.2.4.RELEASE、Spring Cloud Hoxton.SR1。

Feign 的使用主要分為以下幾個(gè)步驟:

  • 服務(wù)消費(fèi)者添加 Feign 依賴;
  • 創(chuàng)建業(yè)務(wù)層接口,添加 @FeignClient 注解聲明需要調(diào)用的服務(wù);
  • 業(yè)務(wù)層抽象方法使用 SpringMVC 注解配置服務(wù)地址及參數(shù);
  • 啟動類添加 @EnableFeignClients 注解激活 Feign 組件。

創(chuàng)建項(xiàng)目

PS:服務(wù)消費(fèi)者通過 Eureka 注冊中心獲取服務(wù),或者 Ribbon 點(diǎn)對點(diǎn)直連模式都可以使用 Feign 來實(shí)現(xiàn)。

我們創(chuàng)建聚合項(xiàng)目并使用 Eureka 注冊中心來講解 Feign,首先創(chuàng)建一個(gè) pom 父工程。

添加依賴

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.example</groupId>
    <artifactId>feign-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- 繼承 spring-boot-starter-parent 依賴 -->
    <!-- 使用繼承方式,實(shí)現(xiàn)復(fù)用,符合繼承的都可以被使用 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
    </parent>

    <!--
        集中定義依賴組件版本號,但不引入,
        在子工程中用到聲明的依賴時(shí),可以不加依賴的版本號,
        這樣可以統(tǒng)一管理工程中用到的依賴版本
     -->
    <properties>
        <!-- Spring Cloud Hoxton.SR1 依賴 -->
        <spring-cloud.version>Hoxton.SR1</spring-cloud.version>
    </properties>

    <!-- 項(xiàng)目依賴管理 父項(xiàng)目只是聲明依賴,子項(xiàng)目需要寫明需要的依賴(可以省略版本信息) -->
    <dependencyManagement>
        <dependencies>
            <!-- spring cloud 依賴 -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>

注冊中心 eureka-server

注冊中心我們采用集群方式構(gòu)建,本文中使用兩個(gè)節(jié)點(diǎn)分別是 eureka-servereureka-server02。

創(chuàng)建項(xiàng)目

eureka-server 和 eureka-server02 的創(chuàng)建過程一致。

添加依賴

eureka-server 和 eureka-server02 的依賴配置一致。

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.example</groupId>
    <artifactId>eureka-server</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- 繼承父依賴 -->
    <parent>
        <groupId>com.example</groupId>
        <artifactId>feign-demo</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <!-- 項(xiàng)目依賴 -->
    <dependencies>
        <!-- netflix eureka server 依賴 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <!-- spring boot web 依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- spring boot test 依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

</project>

配置文件

eureka-server 的 application.yml

server:
  port: 8761 # 端口

spring:
  application:
    name: eureka-server # 應(yīng)用名稱(集群下相同)

# 配置 Eureka Server 注冊中心
eureka:
  instance:
    hostname: eureka01            # 主機(jī)名,不配置的時(shí)候?qū)⒏鶕?jù)操作系統(tǒng)的主機(jī)名來獲取
    prefer-ip-address: true       # 是否使用 ip 地址注冊
    instance-id: ${spring.cloud.client.ip-address}:${server.port} # ip:port
  client:
    # 設(shè)置服務(wù)注冊中心地址,指向另一個(gè)注冊中心
    service-url:                  # 注冊中心對外暴露的注冊地址
      defaultZone: http://localhost:8762/eureka/

eureka-server02 的 application.yml

spring:
  application:
    name: eureka-server # 應(yīng)用名稱(集群下相同)

# 端口
server:
  port: 8762

# 配置 Eureka Server 注冊中心
eureka:
  instance:
    hostname: eureka02            # 主機(jī)名,不配置的時(shí)候?qū)⒏鶕?jù)操作系統(tǒng)的主機(jī)名來獲取
    prefer-ip-address: true       # 是否使用 ip 地址注冊
    instance-id: ${spring.cloud.client.ip-address}:${server.port} # ip:port
  client:
    # 設(shè)置服務(wù)注冊中心地址,指向另一個(gè)注冊中心
    service-url:                  # 注冊中心對外暴露的注冊地址
      defaultZone: http://localhost:8761/eureka/

啟動類

eureka-server 和 eureka-server02 的啟動類一致。

EurekaServerApplication.java

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
// 開啟 EurekaServer 注解
@EnableEurekaServer
public class EurekaServerApplication {

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

}

服務(wù)提供者 service-provider

服務(wù)提供者我們采用集群方式構(gòu)建,本文中使用兩個(gè)節(jié)點(diǎn)分別是 service-providerservice-provider02。

創(chuàng)建項(xiàng)目

service-provider 和 service-provider02 的創(chuàng)建過程一致。

添加依賴

service-provider 和 service-provider02 的依賴配置一致。

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.example</groupId>
    <artifactId>service-provider</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- 繼承父依賴 -->
    <parent>
        <groupId>com.example</groupId>
        <artifactId>feign-demo</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <!-- 項(xiàng)目依賴 -->
    <dependencies>
        <!-- netflix eureka client 依賴 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!-- spring boot web 依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- lombok 依賴 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- spring boot test 依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

</project>

配置文件

service-provider 的 application.yml

server:
  port: 7070 # 端口

spring:
  application:
    name: service-provider # 應(yīng)用名稱(集群下相同)

# 配置 Eureka Server 注冊中心
eureka:
  instance:
    prefer-ip-address: true       # 是否使用 ip 地址注冊
    instance-id: ${spring.cloud.client.ip-address}:${server.port} # ip:port
  client:
    service-url:                  # 設(shè)置服務(wù)注冊中心地址
      defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/

service-provider02 的 application.yml

spring:
  application:
    name: service-provider # 應(yīng)用名稱(集群下相同)

# 端口
server:
  port: 7071

# 配置 Eureka Server 注冊中心
eureka:
  instance:
    prefer-ip-address: true       # 是否使用 ip 地址注冊
    instance-id: ${spring.cloud.client.ip-address}:${server.port} # ip:port
  client:
    service-url:                  # 設(shè)置服務(wù)注冊中心地址
      defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/

實(shí)體類

service-provider 和 service-provider02 的實(shí)體類一致。

Product.java

package com.example.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product implements Serializable {

    private Integer id;
    private String productName;
    private Integer productNum;
    private Double productPrice;

}

編寫服務(wù)

service-provider 和 service-provider02 的服務(wù)代碼一致。

ProductService.java

package com.example.service;

import com.example.pojo.Product;

import java.util.List;

/**
 * 商品服務(wù)
 */
public interface ProductService {

    /**
     * 查詢商品列表
     *
     * @return
     */
    List<Product> selectProductList();

}

ProductServiceImpl.java

package com.example.service.impl;

import com.example.pojo.Product;
import com.example.service.ProductService;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 商品服務(wù)
 */
@Service
public class ProductServiceImpl implements ProductService {

    /**
     * 查詢商品列表
     *
     * @return
     */
    @Override
    public List<Product> selectProductList() {
        return Arrays.asList(
                new Product(1, "華為手機(jī)", 1, 5800D),
                new Product(2, "聯(lián)想筆記本", 1, 6888D),
                new Product(3, "小米平板", 5, 2020D)
        );
    }

}

控制層

service-provider 和 service-provider02 的控制層一致。

ProductController.java

package com.example.controller;

import com.example.pojo.Product;
import com.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
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("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    /**
     * 查詢商品列表
     *
     * @return
     */
    @GetMapping("/list")
    public List<Product> selectProductList() {
        return productService.selectProductList();
    }

}

啟動類

service-provider 和 service-provider02 的啟動類一致。

ServiceProviderApplication.java

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
// 開啟 EurekaClient 注解,目前版本如果配置了 Eureka 注冊中心,默認(rèn)會開啟該注解
//@EnableEurekaClient
public class ServiceProviderApplication {

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

}

服務(wù)消費(fèi)者 service-consumer

創(chuàng)建項(xiàng)目

在剛才的父工程下創(chuàng)建一個(gè) service-consumer 服務(wù)消費(fèi)者的項(xiàng)目。

添加依賴

服務(wù)消費(fèi)者添加 openfeign 依賴。

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.example</groupId>
    <artifactId>service-consumer</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- 繼承父依賴 -->
    <parent>
        <groupId>com.example</groupId>
        <artifactId>feign-demo</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <!-- 項(xiàng)目依賴 -->
    <dependencies>
        <!-- netflix eureka client 依賴 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!-- spring cloud openfeign 依賴 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!-- spring boot web 依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- lombok 依賴 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- spring boot test 依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

</project>

配置文件

application.yml

server:
  port: 9090 # 端口

spring:
  application:
    name: service-consumer # 應(yīng)用名稱

# 配置 Eureka Server 注冊中心
eureka:
  client:
    register-with-eureka: false         # 是否將自己注冊到注冊中心,默認(rèn)為 true
    registry-fetch-interval-seconds: 10 # 表示 Eureka Client 間隔多久去服務(wù)器拉取注冊信息,默認(rèn)為 30 秒
    service-url:                        # 設(shè)置服務(wù)注冊中心地址
      defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/

實(shí)體類

Product.java

package com.example.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product implements Serializable {

    private Integer id;
    private String productName;
    private Integer productNum;
    private Double productPrice;

}

Order.java

package com.example.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Order implements Serializable {

    private Integer id;
    private String orderNo;
    private String orderAddress;
    private Double totalPrice;
    private List<Product> productList;

}

消費(fèi)服務(wù)

ProductService.java

package com.example.service;

import com.example.pojo.Product;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

// 聲明需要調(diào)用的服務(wù)
@FeignClient("service-provider")
public interface ProductService {

    /**
     * 查詢商品列表
     *
     * @return
     */
    // 配置需要調(diào)用的服務(wù)地址及參數(shù)
    @GetMapping("/product/list")
    List<Product> selectProductList();

}

OrderService.java

package com.example.service;

import com.example.pojo.Order;

public interface OrderService {

    /**
     * 根據(jù)主鍵查詢訂單
     *
     * @param id
     * @return
     */
    Order selectOrderById(Integer id);

}

OrderServiceImpl.java

package com.example.service.impl;

import com.example.pojo.Order;
import com.example.service.OrderService;
import com.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductService productService;

    /**
     * 根據(jù)主鍵查詢訂單
     *
     * @param id
     * @return
     */
    @Override
    public Order selectOrderById(Integer id) {
        return new Order(id, "order-001", "中國", 22788D,
                productService.selectProductList());
    }

}

控制層

OrderController.java

package com.example.controller;

import com.example.pojo.Order;
import com.example.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 根據(jù)主鍵查詢訂單
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Order selectOrderById(@PathVariable("id") Integer id) {
        return orderService.selectOrderById(id);
    }

}

啟動類

ServiceConsumerApplication.java

package com.example;

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

@SpringBootApplication
// 開啟 EurekaClient 注解,目前版本如果配置了 Eureka 注冊中心,默認(rèn)會開啟該注解
//@EnableEurekaClient
// 開啟 FeignClients 注解
@EnableFeignClients
public class ServiceConsumerApplication {

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

}

訪問

當(dāng)前環(huán)境運(yùn)行結(jié)果如下:

訪問:http://localhost:9090/order/1

Feign 負(fù)載均衡

Feign 封裝了 Ribbon 自然也就集成了負(fù)載均衡的功能,默認(rèn)采用輪詢策略。如何修改負(fù)載均衡策略呢?與之前學(xué)習(xí) Ribbon 時(shí)講解的配置是一致的。

全局

在啟動類或配置類中注入負(fù)載均衡策略對象。所有服務(wù)請求均使用該策略。

@Bean
public RandomRule randomRule() {
    return new RandomRule();
}

局部

修改配置文件指定服務(wù)的負(fù)載均衡策略。格式:服務(wù)應(yīng)用名.ribbon.NFLoadBalancerRuleClassName

# 負(fù)載均衡策略
# service-provider 為調(diào)用的服務(wù)的名稱
service-provider:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

Feign 請求傳參

GET

使用 @PathVariable 注解或 @RequestParam 注解接收請求參數(shù)。

服務(wù)提供者

ProductService.java

/**
 * 根據(jù)主鍵查詢商品
 *
 * @param id
 * @return
 */
Product selectProductById(Integer id);

ProductServiceImpl.java

/**
 * 根據(jù)主鍵查詢商品
 *
 * @param id
 * @return
 */
@Override
public Product selectProductById(Integer id) {
    return new Product(id, "冰箱", 1, 2666D);
}

ProductController.java

package com.example.controller;

import com.example.pojo.Product;
import com.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    /**
     * 根據(jù)主鍵查詢商品
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Product selectProductById(@PathVariable("id") Integer id) {
        return productService.selectProductById(id);
    }

}

服務(wù)消費(fèi)者

ProductService.java

package com.example.service;

import com.example.pojo.Product;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;

// 聲明需要調(diào)用的服務(wù)
@FeignClient("service-provider")
public interface ProductService {

    /**
     * 根據(jù)主鍵查詢商品
     *
     * @return
     */
    @GetMapping("/product/{id}")
    Product selectProductById(@PathVariable("id") Integer id);

}

OrderServiceImpl.java

package com.example.service.impl;

import com.example.pojo.Order;
import com.example.service.OrderService;
import com.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductService productService;

    /**
     * 根據(jù)主鍵查詢訂單
     *
     * @param id
     * @return
     */
    @Override
    public Order selectOrderById(Integer id) {
        return new Order(id, "order-003", "中國", 2666D,
                Arrays.asList(productService.selectProductById(5)));
    }

}

訪問

訪問:http://localhost:9090/order/3 結(jié)果如下:

POST

使用 @RequestBody 注解接收請求參數(shù)。

服務(wù)提供者

ProductService.java

/**
 * 根據(jù)主鍵查詢商品
 *
 * @param id
 * @return
 */
Product queryProductById(Integer id);

/**
 * 新增商品
 *
 * @param product
 * @return
 */
Map<Object, Object> createProduct(Product product);

ProductServiceImpl.java

/**
 * 根據(jù)主鍵查詢商品
 *
 * @param id
 * @return
 */
@Override
public Product queryProductById(Integer id) {
    return new Product(id, "冰箱", 1, 2666D);
}

/**
 * 新增商品
 *
 * @param product
 * @return
 */
@Override
public Map<Object, Object> createProduct(Product product) {
    System.out.println(product);
    return new HashMap<Object, Object>() {{
        put("code", 200);
        put("message", "新增成功");
    }};
}

ProductController.java

package com.example.controller;

import com.example.pojo.Product;
import com.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    /**
     * 根據(jù)主鍵查詢商品
     *
     * @param id
     * @return
     */
    @PostMapping("/single")
    public Product queryProductById(@RequestBody Integer id) {
        return productService.queryProductById(id);
    }

    /**
     * 新增商品
     *
     * @param product
     * @return
     */
    @PostMapping("/save")
    public Map<Object, Object> createProduct(@RequestBody Product product) {
        return productService.createProduct(product);
    }

}

服務(wù)消費(fèi)者

ProductService.java

package com.example.service;

import com.example.pojo.Product;
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.PostMapping;

import java.util.List;
import java.util.Map;

// 聲明需要調(diào)用的服務(wù)
@FeignClient("service-provider")
public interface ProductService {

    /**
     * 根據(jù)主鍵查詢商品
     *
     * @param id
     * @return
     */
    @PostMapping("/product/single")
    Product queryProductById(Integer id);

    /**
     * 新增商品
     *
     * @param user
     * @return
     */
    @PostMapping("/product/save")
    Map<Object, Object> createProduct(Product user);

}

為了方便測試,直接創(chuàng)建入口調(diào)用,不通過訂單服務(wù)去調(diào)用商品服務(wù)了。

ProductController.java

package com.example.controller;

import com.example.pojo.Product;
import com.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    /**
     * 根據(jù)主鍵查詢商品
     *
     * @param id
     * @return
     */
    @PostMapping("/info")
    public Product queryProductById(Integer id) {
        return productService.queryProductById(id);
    }

    /**
     * 新增商品
     *
     * @param product
     * @return
     */
    @PostMapping("/save")
    public Map<Object, Object> createProduct(Product product) {
        return productService.createProduct(product);
    }

}

訪問

訪問:http://localhost:9090/product/info 請求參數(shù)為 id=5 結(jié)果如下:

訪問:http://localhost:9090/product/save 請求參數(shù)為 id=6&productName=耳機(jī)&productNum=1&productPrice=288 結(jié)果如下:

下一篇我們講解 Feign 性能優(yōu)化的問題,Gzip壓縮、HTTP連接池、請求超時(shí)等,記得關(guān)注噢~

本文采用 知識共享「署名-非商業(yè)性使用-禁止演繹 4.0 國際」許可協(xié)議。

大家可以通過 分類 查看更多關(guān)于 Spring Cloud 的文章。


?? 您的點(diǎn)贊轉(zhuǎn)發(fā)是對我最大的支持。

?? 關(guān)注公眾號 哈嘍沃德先生「文檔 + 視頻」每篇文章都配有專門視頻講解,學(xué)習(xí)更輕松噢 ~


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容