最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

解決微服務(wù)feign調(diào)用添加token的問題

 更新時(shí)間:2021年06月30日 10:21:37   作者:synda@hzy  
這篇文章主要介紹了解決微服務(wù)feign調(diào)用添加token的問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

微服務(wù)feign調(diào)用添加token

1.一般情況是這么配置的

具體的怎么調(diào)用就不說了 如下配置,就可以在請求頭中添加需要的請求頭信息。

package localdate;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
/**
 * feign調(diào)用服務(wù)時(shí),會丟失請求頭信息。需要在這里把認(rèn)證信息收到添加上去
 * @author TRON
 * @since  2019-11-23
 *
 *
 */
@Configuration
@Slf4j
public class FeignTokenInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        log.info("======上下文中獲取原請求信息======");
        String token = "without token";
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String HeadValue = request.getHeader(headerName);
            log.info("===原請求頭信息=== headName: {}, headValue: {}", headerName, HeadValue);
            if (headerName.equals("X-Authorization-access_token")||headerName.equals("x-authorization-access_token")) {
                token = HeadValue;
            }
        }
        log.info("=======Feign添加頭部信息start======");
//        requestTemplate.header("X-Authorization-access_token", token);
        requestTemplate.header("X-Authorization-access_token", "tron123456");
        log.info("=======Feign添加頭部信息end======");
    }
}

2 .但是,當(dāng)熔斷開啟后,原先的這么配置就不起作用了

package localdate;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.strategy.HystrixPlugins;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariable;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableLifecycle;
import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier;
import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook;
import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher;
import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy;
import com.netflix.hystrix.strategy.properties.HystrixProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
 * 自定義并發(fā)策略
 * 將現(xiàn)有的并發(fā)策略作為新并發(fā)策略的成員變量
 * 在新并發(fā)策略中,返回現(xiàn)有并發(fā)策略的線程池、Queue
 *
 * hystrix.command.default.execution.isolation.strategy=THREAD
 * Hystrix的默認(rèn)隔離策略(官方推薦,當(dāng)使用該隔離策略時(shí),是沒辦法拿到 ThreadLocal 中的值的,但是RequestContextHolder 源碼中,使用了兩個(gè)ThreadLocal)
 * hystrix.command.default.execution.isolation.strategy=SEMAPHORE (將隔離策略改為SEMAPHORE 也可以解決這個(gè)問題,但是官方并不推薦這個(gè)策略,因?yàn)檫@個(gè)策略對網(wǎng)絡(luò)資源消耗比較大)
 *
 * 主要是解決當(dāng) Hystrix的默認(rèn)隔離策略是THREAD時(shí),不能通過RequestContextHolder獲取到request對象的問題
 *
 */
//@Configuration
public class FeignConfig extends HystrixConcurrencyStrategy {
    private static final Logger log = LoggerFactory.getLogger(FeignConfig.class);
    private HystrixConcurrencyStrategy delegate;
    public FeignConfig() {
        try {
            this.delegate = HystrixPlugins.getInstance().getConcurrencyStrategy();
            if (this.delegate instanceof FeignConfig) {
                // Welcome to singleton hell...
                return;
            }
            HystrixCommandExecutionHook commandExecutionHook =
                    HystrixPlugins.getInstance().getCommandExecutionHook();
            HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance().getEventNotifier();
            HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance().getMetricsPublisher();
            HystrixPropertiesStrategy propertiesStrategy =
                    HystrixPlugins.getInstance().getPropertiesStrategy();
            this.logCurrentStateOfHystrixPlugins(eventNotifier, metricsPublisher, propertiesStrategy);
            HystrixPlugins.reset();
            HystrixPlugins.getInstance().registerConcurrencyStrategy(this);
            HystrixPlugins.getInstance().registerCommandExecutionHook(commandExecutionHook);
            HystrixPlugins.getInstance().registerEventNotifier(eventNotifier);
            HystrixPlugins.getInstance().registerMetricsPublisher(metricsPublisher);
            HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy);
        } catch (Exception e) {
            log.error("Failed to register Sleuth Hystrix Concurrency Strategy", e);
        }
    }
    private void logCurrentStateOfHystrixPlugins(HystrixEventNotifier eventNotifier,
                                                 HystrixMetricsPublisher metricsPublisher, HystrixPropertiesStrategy propertiesStrategy) {
        if (log.isDebugEnabled()) {
            log.debug("Current Hystrix plugins configuration is [" + "concurrencyStrategy ["
                    + this.delegate + "]," + "eventNotifier [" + eventNotifier + "]," + "metricPublisher ["
                    + metricsPublisher + "]," + "propertiesStrategy [" + propertiesStrategy + "]," + "]");
            log.debug("Registering Sleuth Hystrix Concurrency Strategy.");
        }
    }
    @Override
    public <T> Callable<T> wrapCallable(Callable<T> callable) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return new WrappedCallable<>(callable, requestAttributes);
    }
    @Override
    public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
                                            HystrixProperty<Integer> corePoolSize, HystrixProperty<Integer> maximumPoolSize,
                                            HystrixProperty<Integer> keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        return this.delegate.getThreadPool(threadPoolKey, corePoolSize, maximumPoolSize, keepAliveTime,
                unit, workQueue);
    }
    @Override
    public BlockingQueue<Runnable> getBlockingQueue(int maxQueueSize) {
        return this.delegate.getBlockingQueue(maxQueueSize);
    }
    @Override
    public <T> HystrixRequestVariable<T> getRequestVariable(HystrixRequestVariableLifecycle<T> rv) {
        return this.delegate.getRequestVariable(rv);
    }
    static class WrappedCallable<T> implements Callable<T> {
        private final Callable<T> target;
        private final RequestAttributes requestAttributes;
        public WrappedCallable(Callable<T> target, RequestAttributes requestAttributes) {
            this.target = target;
            this.requestAttributes = requestAttributes;
        }
        @Override
        public T call() throws Exception {
            try {
                RequestContextHolder.setRequestAttributes(requestAttributes);
                return target.call();
            } finally {
                RequestContextHolder.resetRequestAttributes();
            }
        }
    }
}

3 .feign和熔斷的配置

feign:
  client:
    config:
      default:
        connectTimeout: 5000   #連接超時(shí)3秒,連接失敗時(shí)直接調(diào)用降級方法
        readTimeout: 100000     #連接成功,處理數(shù)據(jù)的時(shí)間限制10秒 100000   讀取時(shí)間過短會拋異常java.net.SocketTimeoutException: Read timed out
        loggerLevel: full      #日志輸出等級
  hystrix:
    enabled: true
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 5000  #服務(wù)連接成功,但是時(shí)間過長,降級方法調(diào)用時(shí)間   60000   5000

feign微服務(wù)的相互調(diào)用

我只是記錄服務(wù)提供方、消費(fèi)方的代碼編寫,配置什么的大家在網(wǎng)上搜,一大堆。

首先是服務(wù)提供方:

啟動類上加上注解@EnableFeignClients,然后正常的寫controller、service等業(yè)務(wù)邏輯

其次是服務(wù)的調(diào)用方:

1.首先啟動類上加上注解@EnableFeignClients

2.編寫服務(wù)調(diào)用接口

3.編寫接口熔斷處理方法

4.本人遇到的問題是需要用到調(diào)用方的請求頭里面的信息,但是在提供方取不到,這時(shí)可以通過在調(diào)用方增加配置來解決

import feign.RequestInterceptor;
import feign.RequestTemplate;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
 
/**
 * @author ydf
 * @date 2021/5/13
 * @description:
 **/
public class FeignBasicAuthRequestInterceptor implements RequestInterceptor {
 
  @Override
  public void apply(RequestTemplate requestTemplate) {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
        .getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames != null) {
      while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        String values = request.getHeader(name);
        requestTemplate.header(name, values);
      }
    }
  }
}

import com.jingling.netsign.applet.interceptor.FeignBasicAuthRequestInterceptor;
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; 
/**
 * @author ydf
 * @date 2021/5/13
 * @description:
 **/
@Configuration
public class FeignSupportConfig {
  /**
   * feign請求攔截器
   *
   * @return
   */
  @Bean
  public RequestInterceptor requestInterceptor(){
    return new FeignBasicAuthRequestInterceptor();
  }
}

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java Fork/Join框架

    Java Fork/Join框架

    Fork/Join框架是Java7中新增的一項(xiàng)特性,也是Java7平臺的其中一項(xiàng)主要改進(jìn)。下面我們就來簡單探討下Java的Fork/Join框架
    2016-09-09
  • SpringBoot整合RabbitMQ實(shí)現(xiàn)延遲隊(duì)列和死信隊(duì)列

    SpringBoot整合RabbitMQ實(shí)現(xiàn)延遲隊(duì)列和死信隊(duì)列

    RabbitMQ的死信隊(duì)列用于接收其他隊(duì)列中的“死信”消息,所謂“死信”,是指滿足一定條件而無法被消費(fèi)者正確處理的消息,死信隊(duì)列通常與RabbitMQ的延遲隊(duì)列一起使用,本文給大家介紹了SpringBoot整合RabbitMQ實(shí)現(xiàn)延遲隊(duì)列和死信隊(duì)列,需要的朋友可以參考下
    2024-06-06
  • 如何給yml配置文件的密碼加密(SpringBoot)

    如何給yml配置文件的密碼加密(SpringBoot)

    這篇文章主要介紹了如何給yml配置文件的密碼加密(SpringBoot),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-10-10
  • SpringBoot后端接收參數(shù)優(yōu)化代碼示例(統(tǒng)一處理前端參數(shù))

    SpringBoot后端接收參數(shù)優(yōu)化代碼示例(統(tǒng)一處理前端參數(shù))

    使用Spring Boot開發(fā)API的時(shí)候,讀取請求參數(shù)是服務(wù)端編碼中最基本的一項(xiàng)操作,下面這篇文章主要給大家介紹了關(guān)于SpringBoot后端接收參數(shù)優(yōu)化(統(tǒng)一處理前端參數(shù))的相關(guān)資料,需要的朋友可以參考下
    2024-07-07
  • java對接webservice接口的4種方式總結(jié)

    java對接webservice接口的4種方式總結(jié)

    因工作需要和一個(gè)Sap相關(guān)系統(tǒng)以WebService的方式進(jìn)行接口聯(lián)調(diào),之前僅聽過這種技術(shù),但并沒有實(shí)操過,所以將本次開發(fā)進(jìn)行記錄,這篇文章主要給大家介紹了關(guān)于java對接webservice接口的4種方式,需要的朋友可以參考下
    2023-10-10
  • SpringBoot一個(gè)接口多個(gè)實(shí)現(xiàn)類的調(diào)用方式總結(jié)

    SpringBoot一個(gè)接口多個(gè)實(shí)現(xiàn)類的調(diào)用方式總結(jié)

    這篇文章主要介紹了SpringBoot一個(gè)接口多個(gè)實(shí)現(xiàn)類的調(diào)用方式,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2024-01-01
  • Spring Data JPA分頁復(fù)合查詢原理解析

    Spring Data JPA分頁復(fù)合查詢原理解析

    這篇文章主要介紹了Spring Data JPA分頁復(fù)合查詢原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-11-11
  • SpringBoot上傳臨時(shí)文件被刪除引起報(bào)錯(cuò)的解決

    SpringBoot上傳臨時(shí)文件被刪除引起報(bào)錯(cuò)的解決

    這篇文章主要介紹了SpringBoot上傳臨時(shí)文件被刪除引起報(bào)錯(cuò)的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • 使用游長編碼對字符串壓縮 Run Length編碼示例

    使用游長編碼對字符串壓縮 Run Length編碼示例

    這篇文章主要介紹了Run Length編碼的一個(gè)示例,大家參考使用吧
    2014-01-01
  • SpringBoot集成slf4j2日志配置的實(shí)現(xiàn)示例

    SpringBoot集成slf4j2日志配置的實(shí)現(xiàn)示例

    本文主要介紹了SpringBoot集成slf4j2日志配置的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-08-08

最新評論

塔河县| 临西县| 仁化县| 连城县| 万源市| 三台县| 阿合奇县| 赤峰市| 广宗县| 化隆| 桦南县| 乌兰浩特市| 得荣县| 阆中市| 浏阳市| 德庆县| 五常市| 长阳| 沁源县| 肃北| 泗阳县| 阿拉尔市| 土默特左旗| 金平| 昭平县| 榆树市| 垫江县| 巴彦淖尔市| 峨眉山市| 新源县| 鄄城县| 桓台县| 宁河县| 清远市| 顺义区| 青神县| 安图县| 宜川县| 奈曼旗| 荔浦县| 南投市|