Spring Cloud 系列之 Feign 聲明式服務調用(一)

什麼是 Feign

Feign 是 Spring Cloud Netflix 組件中的一個輕量級 RESTful 的 HTTP 服務客戶端,實現了負載均衡和 Rest 調用的開源框架,封裝了 Ribbon 和 RestTemplate,實現了 WebService 的面向接口編程,進一步降低了項目的耦合度。

Feign 內置了 Ribbon,用來做客戶端負載均衡調用服務註冊中心的服務。

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

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

Feign 支持的註解和用法請參考官方文檔:https://github.com/OpenFeign/feign 或 spring.io 官網文檔

Feign 的使用方式是:使用 Feign 的註解定義接口,調用這個接口,就可以調用服務註冊中心的服務。

Feign 解決什麼問題

Feign 旨在使編寫 JAVA HTTP 客戶端變得更加容易,Feign 簡化了 RestTemplate 代碼,實現了 Ribbon 負載均衡,使代碼變得更加簡潔,也少了客戶端調用的代碼,使用 Feign 實現負載均衡是首選方案。只需要你創建一個接口,然後在上面添加註解即可。

Feign 是聲明式服務調用組件,其核心就是:像調用本地方法一樣調用遠程方法,無感知遠程 HTTP 請求。

  • 它解決了讓開發者調用遠程接口就跟調用本地方法一樣的體驗,開發者完全感知不到這是遠程方法,更感知不到這是個 HTTP 請求。無需關注與遠程的交互細節,更無需關注分佈式環境開發。

  • 它像 Dubbo 一樣,Consumer 直接調用 Provider 接口方法,而不需要通過常規的 Http Client 構造請求再解析返回數據。

Feign vs OpenFeign

OpenFeign 是 Spring Cloud 在 Feign 的基礎上支持了 Spring MVC 的註解,如 @RequesMapping@Pathvariable 等等。

OpenFeign 的 @FeignClient 可以解析 SpringMVC 的 @RequestMapping 註解下的接口,並通過動態代理的方式產生實現類,實現類中做負載均衡並調用服務。

Feign 入門案例

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

feign-demo 聚合工程。SpringBoot 2.2.4.RELEASESpring Cloud Hoxton.SR1

Feign 的使用主要分爲以下幾個步驟:

  • 服務消費者添加 Feign 依賴;
  • 創建業務層接口,添加 @FeignClient 註解聲明需要調用的服務;
  • 業務層抽象方法使用 SpringMVC 註解配置服務地址及參數;
  • 啓動類添加 @EnableFeignClients 註解激活 Feign 組件。

創建項目

PS:服務消費者通過 Eureka 註冊中心獲取服務,或者 Ribbon 點對點直連模式都可以使用 Feign 來實現。

我們創建聚合項目並使用 Eureka 註冊中心來講解 Feign,首先創建一個 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 依賴 -->
    <!-- 使用繼承方式,實現複用,符合繼承的都可以被使用 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
    </parent>

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

    <!-- 項目依賴管理 父項目只是聲明依賴,子項目需要寫明需要的依賴(可以省略版本信息) -->
    <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

註冊中心我們採用集羣方式構建,本文中使用兩個節點分別是 eureka-servereureka-server02

創建項目

eureka-server 和 eureka-server02 的創建過程一致。

添加依賴

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>

    <!-- 項目依賴 -->
    <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 # 應用名稱(集羣下相同)

# 配置 Eureka Server 註冊中心
eureka:
  instance:
    hostname: eureka01            # 主機名,不配置的時候將根據操作系統的主機名來獲取
    prefer-ip-address: true       # 是否使用 ip 地址註冊
    instance-id: ${spring.cloud.client.ip-address}:${server.port} # ip:port
  client:
    # 設置服務註冊中心地址,指向另一個註冊中心
    service-url:                  # 註冊中心對外暴露的註冊地址
      defaultZone: http://localhost:8762/eureka/

eureka-server02 的 application.yml

spring:
  application:
    name: eureka-server # 應用名稱(集羣下相同)

# 端口
server:
  port: 8762

# 配置 Eureka Server 註冊中心
eureka:
  instance:
    hostname: eureka02            # 主機名,不配置的時候將根據操作系統的主機名來獲取
    prefer-ip-address: true       # 是否使用 ip 地址註冊
    instance-id: ${spring.cloud.client.ip-address}:${server.port} # ip:port
  client:
    # 設置服務註冊中心地址,指向另一個註冊中心
    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);
    }

}

服務提供者 service-provider

服務提供者我們採用集羣方式構建,本文中使用兩個節點分別是 service-providerservice-provider02

創建項目

service-provider 和 service-provider02 的創建過程一致。

添加依賴

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>

    <!-- 項目依賴 -->
    <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 # 應用名稱(集羣下相同)

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

service-provider02 的 application.yml

spring:
  application:
    name: service-provider # 應用名稱(集羣下相同)

# 端口
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:                  # 設置服務註冊中心地址
      defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/

實體類

service-provider 和 service-provider02 的實體類一致。

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;

}

編寫服務

service-provider 和 service-provider02 的服務代碼一致。

ProductService.java

package com.example.service;

import com.example.pojo.Product;

import java.util.List;

/**
 * 商品服務
 */
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;

/**
 * 商品服務
 */
@Service
public class ProductServiceImpl implements ProductService {

    /**
     * 查詢商品列表
     *
     * @return
     */
    @Override
    public List<Product> selectProductList() {
        return Arrays.asList(
                new Product(1, "華爲手機", 1, 5800D),
                new Product(2, "聯想筆記本", 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 註冊中心,默認會開啓該註解
//@EnableEurekaClient
public class ServiceProviderApplication {

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

}

服務消費者 service-consumer

創建項目

在剛纔的父工程下創建一個 service-consumer 服務消費者的項目。

添加依賴

服務消費者添加 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>

    <!-- 項目依賴 -->
    <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 # 應用名稱

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

實體類

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;

}

消費服務

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;

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

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

}

OrderService.java

package com.example.service;

import com.example.pojo.Order;

public interface OrderService {

    /**
     * 根據主鍵查詢訂單
     *
     * @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;

    /**
     * 根據主鍵查詢訂單
     *
     * @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;

    /**
     * 根據主鍵查詢訂單
     *
     * @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 註冊中心,默認會開啓該註解
//@EnableEurekaClient
// 開啓 FeignClients 註解
@EnableFeignClients
public class ServiceConsumerApplication {

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

}

訪問

當前環境運行結果如下:

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

Feign 負載均衡

Feign 封裝了 Ribbon 自然也就集成了負載均衡的功能,默認採用輪詢策略。如何修改負載均衡策略呢?與之前學習 Ribbon 時講解的配置是一致的。

全局

在啓動類或配置類中注入負載均衡策略對象。所有服務請求均使用該策略。

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

局部

修改配置文件指定服務的負載均衡策略。格式:服務應用名.ribbon.NFLoadBalancerRuleClassName

# 負載均衡策略
# service-provider 爲調用的服務的名稱
service-provider:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

Feign 請求傳參

GET

使用 @PathVariable 註解或 @RequestParam 註解接收請求參數。

服務提供者

ProductService.java

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

ProductServiceImpl.java

/**
 * 根據主鍵查詢商品
 *
 * @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;

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

}

服務消費者

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;

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

    /**
     * 根據主鍵查詢商品
     *
     * @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;

    /**
     * 根據主鍵查詢訂單
     *
     * @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 結果如下:

POST

使用 @RequestBody 註解接收請求參數。

服務提供者

ProductService.java

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

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

ProductServiceImpl.java

/**
 * 根據主鍵查詢商品
 *
 * @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;

    /**
     * 根據主鍵查詢商品
     *
     * @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);
    }

}

服務消費者

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;

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

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

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

}

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;

    /**
     * 根據主鍵查詢商品
     *
     * @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 請求參數爲 id=5 結果如下:

訪問:http://localhost:9090/product/save 請求參數爲 id=6&productName=耳機&productNum=1&productPrice=288 結果如下:

下一篇我們講解 Feign 性能優化的問題,Gzip壓縮、HTTP連接池、請求超時等,記得關注噢~

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

大家可以通過 分類 查看更多關於 Spring Cloud 的文章。


🤗 您的點贊轉發是對我最大的支持。

📢 掃碼關注 哈嘍沃德先生「文檔 + 視頻」每篇文章都配有專門視頻講解,學習更輕鬆噢 ~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章