OpenFeign微服务调用组件使用

前言:OpenFeign是可以跨服务、跨进程的调用方式。

什么是Feign

Feign是Netflix开发的声明式、模版化的HTTP客户端。
优势:

Feign可以做到使用 HTTP 请求远程服务时就像调用本地方法一样的体验,开发者完全感知不到这是远程方法,更感知不到这是个 HTTP 请求,开发者无需关注与远程的交互细节,更无需关注分布式环境开发。

Spring Cloud Alibaba快速整合OpenFeign

1、引入依赖,谁远程调用谁引入这个依赖

java 复制代码
<!-- openfeign 远程调用 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

2、编写调用接口

java 复制代码
package com.by.controller;


import cn.by.moder.OrderDTO;
import cn.by.moder.OrderOkDTO;
import cn.by.moder.OrderQueryDTO;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;

import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

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


    @GetMapping("/test")
    public String test() {
        return "咸蛋超人杨order";
    }

    @GetMapping("/ordering")
    public String ordering() {
        return "咸蛋超人杨";
    }

    @GetMapping("/ordering1")
    public OrderOkDTO ordering1() {

        OrderOkDTO build = OrderOkDTO.builder().id(10086L).needPay(new BigDecimal(100)).build();
        return build;
    }

    @PostMapping("/ordering2")
    public OrderOkDTO ordering2(@RequestBody OrderDTO orderDTO) {
        List<String> names = orderDTO.getProducts().stream().map(item->item.getName()).collect(Collectors.toList());
        String join = StrUtil.join(",", names);
        OrderOkDTO build = OrderOkDTO.builder().id(10086L).needPay(new BigDecimal(100)).msg(join).build();
        return build;
    }
    @GetMapping("/select")
    public String select(OrderQueryDTO queryDTO) {
        String empty = StrUtil.EMPTY;
        if (queryDTO.getId() != null) {
            empty = "通过Id查询"+queryDTO.getId();
        }
        if (queryDTO.getUserId()!= null) {
            empty = "通过UserId查询"+queryDTO.getUserId();
        }
        return empty;
    }

    @GetMapping("/sleep")
    public String sleep(@RequestParam Integer time) {

        ThreadUtil.safeSleep(time*1000);
        return  "你睡眠了"+time+"秒";
    }
}

3、在创建一个调用端,调用端在启动类上添加@EnableFeignClients注解,并创建service接口+@FeignClient注解

接口

java 复制代码
package com.by.service;

import cn.by.moder.OrderDTO;
import cn.by.moder.OrderOkDTO;
import cn.by.moder.OrderQueryDTO;
import com.by.config.FeignConfig;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.*;

//如果想单独配置某个服务的日志级别,使用configuration单独配置
// @FeignClient(name = "order-service-app",configuration = FeignConfig.class)
@FeignClient(name = "order-service-app")
@RequestMapping("/api/order")
public interface OrderService {

    @GetMapping("/ordering")
     String ordering();

    @GetMapping("/ordering1")
    OrderOkDTO ordering1();

    @PostMapping("/ordering2")
    OrderOkDTO ordering2(@RequestBody OrderDTO orderDTO);

    @GetMapping("/select")
    String select(@SpringQueryMap OrderQueryDTO queryDTO);

    @GetMapping("/sleep")
    String sleep(@RequestParam Integer time);
}

4、发起调用,像调用本地方法一样调用远程服务

高级配置

1、全局配置

注意一:此处配置@Configuration注解就会全局生效,如果想指定对应某一个服务生效,就不能配置.

注意二: 因为feign调试日志是debug级别输出,springboot默认的日志级别是info,所以feign的debug日志级别就不会输出,一定要结合

java 复制代码
package com.by.config;

import feign.Logger;
import feign.Request;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration //全局配置 结合properties中的logging.level.com.by = debug使用
public class FeignConfig {

    //  @Bean
    // Logger.Level feignLoggerLevel(){
    //      // 这里记录所有请求和响应的详细信息,包括头信息等
    //      return Logger.Level.FULL;
    //  }

    @Bean
    public Request.Options options(){
        return new Request.Options(10, TimeUnit.SECONDS,20, TimeUnit.SECONDS,true);
    }
}

2 、局部配置

局部配置,让调用的微服务生效,在@FeignClient 注解中指定使用的配置类

3、 在配置文件配置

复制代码
logging.level.com.beiyou = debug
开启日志

##配置feign 的日志级别
#-- default 全局配置
feign.client.config.default.loggerLevel=NONE
#-- nacos-a 具体服务名
feign.client.config.nacos-a.loggerLevel=FULL

超时配置
全局配置

配置文件配置

复制代码
#全局配置
feign.client.config.default.connectTimeout=5000
feign.client.config.default.readTimeout=10000

这里default 是一个特殊的客户端名称,用于表示全局配置。设置 connectTimeout 和 readTimeout 属性的值来定义全局的连接超时时间和读取超时时间。

#局部配置 请将 <clientName> 替换为实际的Feign客户端名称。
feign.client.config.<clientName>.connectTimeout=5000
feign.client.config.<clientName>.readTimeout=10000

feign.client.config.order-service.connectTimeout=5000   # 连接超时时间,默认10s order-service:  #对应微服务
feign.client.config.order-service.readTimeout=10000     # 请求处理超时时间,默认60s
相关推荐
一个骇客1 小时前
让你的数据成为“操作日志”和“模型饲料”:事件溯源、CQRS与DataFrame漫谈
架构
ShiLiu_mtx1 小时前
k8s - 7
云原生·容器·kubernetes
鹏北海-RemHusband2 小时前
从零到一:基于 micro-app 的企业级微前端模板完整实现指南
前端·微服务·架构
7哥♡ۣۖᝰꫛꫀꪝۣℋ2 小时前
Spring-cloud\Eureka
java·spring·微服务·eureka
2的n次方_4 小时前
Runtime 内存管理深化:推理批处理下的内存复用与生命周期精细控制
c语言·网络·架构
前端市界5 小时前
用 React 手搓一个 3D 翻页书籍组件,呼吸海浪式翻页,交互体验带感!
前端·架构·github
文艺理科生5 小时前
Nginx 路径映射深度解析:从本地开发到生产交付的底层哲学
前端·后端·架构
C澒5 小时前
Vue 项目渐进式迁移 React:组件库接入与跨框架协同技术方案
前端·vue.js·react.js·架构·系统架构
消失的旧时光-19436 小时前
从 Kotlin 到 Dart:为什么 sealed 是处理「多种返回结果」的最佳方式?
android·开发语言·flutter·架构·kotlin·sealed
惊讶的猫6 小时前
OpenFeign(声明式HTTP客户端)
网络·网络协议·http·微服务·openfeign