国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

解鎖新技能RestTemplate設(shè)置全局、單個(gè)請(qǐng)求超時(shí)時(shí)間及支持https請(qǐng)求

這篇具有很好參考價(jià)值的文章主要介紹了解鎖新技能RestTemplate設(shè)置全局、單個(gè)請(qǐng)求超時(shí)時(shí)間及支持https請(qǐng)求。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

springboot請(qǐng)求第三方接口時(shí)會(huì)用到RestTemplate,其底層實(shí)現(xiàn)邏輯默認(rèn)是通過(guò)SimpleClientHttpRequestFactory來(lái)實(shí)現(xiàn),具體由socket連接來(lái)實(shí)現(xiàn);可以替換其默認(rèn)實(shí)現(xiàn)為HttpComponentsClientHttpRequestFactory。

一、自定義RestTemplate實(shí)例對(duì)象
    @Primary
    @Bean
    public RestTemplate restTemplate(ObjectProvider<HttpClientCustomizer> httpClientCustomizers, ClientHttpRequestFactory clientHttpRequestFactory, HttpClientProperties httpClientProperties) {
        RestTemplate restTemplate = new RestTemplate();
        //設(shè)置BufferingClientHttpRequestFactory將輸入流和輸出流保存到內(nèi)存中,允許多次讀取
        restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(clientHttpRequestFactory));
        //設(shè)置自定義異常處理
        restTemplate.setErrorHandler(new CustomResponseErrorHandler());
        if (httpClientProperties.isInterceptor()) {
            //添加攔截器
          restTemplate.setInterceptors(Collections.singletonList(httpClientCustomizers.orderedStream().findFirst().get()));
        }

        return restTemplate;
    }
二、RestTemplate自定義全局超時(shí)時(shí)間
    @Bean
    public ClientHttpRequestFactory clientHttpRequestFactory(HttpClientProperties properties) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        //SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        //讀取超時(shí)5秒,默認(rèn)無(wú)限限制,單位:毫秒
        factory.setReadTimeout(properties.getReadTimeOut());
        //連接超時(shí)10秒,默認(rèn)無(wú)限制,單位:毫秒
        factory.setConnectTimeout(properties.getConnectTimeOut());
        return factory;
    }
三、RestTemplate設(shè)置單個(gè)請(qǐng)求的超時(shí)時(shí)間

首先看下HttpComponentsClientHttpRequestFactory類(lèi)的createRequest方法源碼:

	@Override
	public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
		HttpClient client = getHttpClient();

		HttpUriRequest httpRequest = createHttpUriRequest(httpMethod, uri);
		postProcessHttpRequest(httpRequest);
		HttpContext context = createHttpContext(httpMethod, uri);
		if (context == null) {
			context = HttpClientContext.create();
		}

		// Request configuration not set in the context
		if (context.getAttribute(HttpClientContext.REQUEST_CONFIG) == null) {
			// Use request configuration given by the user, when available
			RequestConfig config = null;
			if (httpRequest instanceof Configurable) {
				config = ((Configurable) httpRequest).getConfig();
			}
			if (config == null) {
				config = createRequestConfig(client);
			}
			if (config != null) {
				context.setAttribute(HttpClientContext.REQUEST_CONFIG, config);
			}
		}

		if (this.bufferRequestBody) {
			return new HttpComponentsClientHttpRequest(client, httpRequest, context);
		}
		else {
			return new HttpComponentsStreamingClientHttpRequest(client, httpRequest, context);
		}
	}

其中createHttpContext方法默認(rèn)返回的是null,因此HttpContext中的RequestConfig配置值為null,所以需要按照接下來(lái)的代碼生成并設(shè)置;RequestConfig配置類(lèi)中的socketTimeout是設(shè)置讀取超時(shí)時(shí)間,connectTimeout是設(shè)置連接超時(shí)時(shí)間的兩個(gè)屬性,明白了這些就應(yīng)該知道怎樣設(shè)置單個(gè)請(qǐng)求超時(shí)時(shí)間了;

定義一個(gè)HttpContextFactory類(lèi),即HttpContext類(lèi)的一個(gè)實(shí)現(xiàn):

public class HttpContextFactory implements BiFunction<HttpMethod, URI, HttpContext> {
    @Override
    public HttpContext apply(HttpMethod httpMethod, URI uri) {
        RequestConfig requestConfig = HttpContextHolder.peek();
        if (Objects.nonNull(requestConfig)) {
            HttpContext context = HttpClientContext.create();
            context.setAttribute(HttpClientContext.REQUEST_CONFIG, requestConfig);
            return context;
        }
        return null;
    }
}

定義一個(gè)持有RequestConfig線程上下文對(duì)象類(lèi):

public class HttpContextHolder {

    private static final ThreadLocal<RequestConfig> threadLocal = new NamedThreadLocal<>("HTTP進(jìn)程執(zhí)行狀態(tài)上下文");

    public static void bind(RequestConfig requestConfig) {
        threadLocal.set(requestConfig);
    }

    public static RequestConfig peek() {
        return threadLocal.get();
    }

    public static void unbind() {
        threadLocal.remove();
    }
}

設(shè)置將HttpContextFactory類(lèi)實(shí)例對(duì)象:

    @Bean
    public ClientHttpRequestFactory clientHttpRequestFactory(HttpClientProperties properties) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        //SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        //讀取超時(shí)5秒,默認(rèn)無(wú)限限制,單位:毫秒
        factory.setReadTimeout(properties.getReadTimeOut());
        //連接超時(shí)10秒,默認(rèn)無(wú)限制,單位:毫秒
        factory.setConnectTimeout(properties.getConnectTimeOut());
        //設(shè)置HTTP進(jìn)程執(zhí)行狀態(tài)工廠類(lèi)
        factory.setHttpContextFactory(new HttpContextFactory());
        return factory;
    }

調(diào)用示例:

@RequestMapping("api/http")
@RestController
public class HttpClientController {
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("get1")
    public BaseResponse get1(HttpServletRequest request) {
        String timeout = request.getParameter("timeout");
        BaseResponse<String> result;
        try {
            HttpContextHolder.bind(RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(-1).build());
            result = restTemplate.getForObject("https://127.0.0.1:8080/api/http/testResponse?timeout=" + timeout, BaseResponse.class);
        } finally {
            HttpContextHolder.unbind();
        }
        return result;
    }
    }

這樣設(shè)置有點(diǎn)麻煩,可以定義一個(gè)注解,以AOP切面的方式來(lái)使用:

定義注解@TargetHttpTimeout:

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface TargetHttpTimeout {
    /**
     * 讀取超時(shí)時(shí)間,默認(rèn):-1
     */
    int readTimeout() default -1;

    /**
     * 連接超時(shí)時(shí)間,默認(rèn):-1
     */
    int connectTimeout() default -1;
}

定義攔截器HttpTimeoutMethodInterceptor:

public class HttpTimeoutMethodInterceptor implements MethodInterceptor {
    @Nullable
    @Override
    public Object invoke(@Nonnull MethodInvocation invocation) throws Throwable {
        try {
            Method method = invocation.getMethod();
            if (method.isAnnotationPresent(TargetHttpTimeout.class)) {
                TargetHttpTimeout targetHttpTimeout = method.getAnnotation(TargetHttpTimeout.class);
                RequestConfig requestConfig = RequestConfig.custom()
                        .setSocketTimeout(targetHttpTimeout.readTimeout())
                        .setConnectTimeout(targetHttpTimeout.connectTimeout())
                        .build();
                HttpContextHolder.bind(requestConfig);
            }
            return invocation.proceed();
        } finally {
            HttpContextHolder.unbind();
        }
    }
}

將AOP切面及切點(diǎn)關(guān)聯(lián)起來(lái)并注入容器:

    @Bean
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    public Advisor httpTimeoutPointCutAdvice() {
        //限定方法級(jí)別的切點(diǎn)
        Pointcut mpc = new AnnotationMatchingPointcut(null, TargetHttpTimeout.class, false);
        //組合切面(并集),即只要有一個(gè)切點(diǎn)的條件符合,則就攔截
        Pointcut pointcut = new ComposablePointcut(mpc);
        //切面增強(qiáng)類(lèi)
        AnnotationPointcutAdvisor advisor = new AnnotationPointcutAdvisor(new HttpTimeoutMethodInterceptor(), pointcut);
        //切面優(yōu)先級(jí)順序
        advisor.setOrder(AopOrderInfo.HTTP_CLIENT_INTERCEPTOR);
        return advisor;
    }

通過(guò)上述幾步的優(yōu)化就可以優(yōu)雅的按照注解的方式設(shè)置單個(gè)請(qǐng)求的超時(shí)時(shí)間:

    @GetMapping("get2")
    @TargetHttpTimeout(readTimeout = 2000, connectTimeout = -1)
    public BaseResponse get2(HttpServletRequest request) {
        String timeout = request.getParameter("timeout");
        BaseResponse<String> result = restTemplate.getForObject("https://127.0.0.1:8080/api/http/testResponse?timeout=1000", BaseResponse.class);

        return result;
    }
四、RestTemplate支持https請(qǐng)求
    @Bean
    public ClientHttpRequestFactory clientHttpRequestFactory(HttpClientProperties properties) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        //SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        //讀取超時(shí)5秒,默認(rèn)無(wú)限限制,單位:毫秒
        factory.setReadTimeout(properties.getReadTimeOut());
        //連接超時(shí)10秒,默認(rèn)無(wú)限制,單位:毫秒
        factory.setConnectTimeout(properties.getConnectTimeOut());
        //設(shè)置HTTP進(jìn)程執(zhí)行狀態(tài)工廠類(lèi)
        factory.setHttpContextFactory(new HttpContextFactory());
        //開(kāi)啟HTTPS請(qǐng)求支持
        if (properties.isSsl()) {
            TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
            SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());

            CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(connectionSocketFactory).build();
            factory.setHttpClient(httpClient);
        }
        return factory;
    }

通過(guò)上述的步驟完整的實(shí)現(xiàn)了http全局超時(shí)時(shí)間的設(shè)置,單個(gè)請(qǐng)求超時(shí)時(shí)間設(shè)置,https請(qǐng)求支持;

GitHub地址:https://github.com/mingyang66/spring-parent文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-407240.html

到了這里,關(guān)于解鎖新技能RestTemplate設(shè)置全局、單個(gè)請(qǐng)求超時(shí)時(shí)間及支持https請(qǐng)求的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • axios請(qǐng)求超時(shí),設(shè)置重新請(qǐng)求的完美解決方法

    axios請(qǐng)求超時(shí),設(shè)置重新請(qǐng)求的完美解決方法

    自從使用Vue2之后,就使用官方推薦的axios的插件來(lái)調(diào)用API,在使用過(guò)程中,如果服務(wù)器或者網(wǎng)絡(luò)不穩(wěn)定掉包了, 你們?cè)撊绾翁幚砟? 下面我給你們分享一下我的經(jīng)歷。 具體原因 最近公司在做一個(gè)項(xiàng)目, 服務(wù)端數(shù)據(jù)接口用的是Php輸出的API, 有時(shí)候在調(diào)用的過(guò)程中會(huì)失敗, 在谷歌瀏

    2024年02月20日
    瀏覽(20)
  • Axios設(shè)置請(qǐng)求超時(shí)時(shí)間 timeout

    1.axios全局設(shè)置網(wǎng)絡(luò)超時(shí) 2.?單獨(dú)對(duì)某個(gè)請(qǐng)求設(shè)置網(wǎng)絡(luò)超時(shí) 3.webpack的dev的proxyTable的超時(shí)時(shí)間設(shè)置

    2024年04月10日
    瀏覽(19)
  • golang 通過(guò)context設(shè)置接口請(qǐng)求超時(shí)時(shí)間

    下面是直接可應(yīng)用的實(shí)例:

    2024年02月10日
    瀏覽(15)
  • Springboot調(diào)整接口響應(yīng)返回時(shí)長(zhǎng)詳解(解決響應(yīng)超時(shí)問(wèn)題)_springboot設(shè)置請(qǐng)求超時(shí)時(shí)間

    1、配置Http會(huì)話超時(shí) 可以通過(guò)兩種方式為Spring Boot應(yīng)用程序 配置HTTP會(huì)話超時(shí) 。 1.1 application.properties中配置會(huì)話超時(shí) 最簡(jiǎn)單的方法是在你的application.properties中加入?yún)?shù) server.servlet.session.timeout 。 還要注意的是, Tomcat不允許你將超時(shí)時(shí)間設(shè)置得少于60秒 。 1.2 以程序方式配置會(huì)

    2024年04月27日
    瀏覽(114)
  • 【API接口工具】postman設(shè)置超時(shí)時(shí)間、請(qǐng)求等默認(rèn)配置

    【API接口工具】postman設(shè)置超時(shí)時(shí)間、請(qǐng)求等默認(rèn)配置

    Postman 會(huì)自動(dòng)為某些設(shè)置選擇默認(rèn)值,以便您可以開(kāi)始工作。根據(jù)您的用例隨時(shí)更改設(shè)置或自定義您的 Postman 體驗(yàn)。 要更改 Postman 中的設(shè)置,請(qǐng)選擇 設(shè)置圖標(biāo) 標(biāo)題中的設(shè)置圖標(biāo),然后選擇設(shè)置。在 Postman 桌面應(yīng)用程序中,您還可以選擇?+逗號(hào) (,)或Ctrl+逗號(hào) (,) 使用“General”

    2024年02月08日
    瀏覽(26)
  • CSDN博客批量查詢質(zhì)量分https://yma16.inscode.cc/請(qǐng)求超時(shí)問(wèn)題(設(shè)置postman超時(shí)時(shí)間)(接口提供者設(shè)置了nginx超時(shí)時(shí)間)

    CSDN博客批量查詢質(zhì)量分https://yma16.inscode.cc/請(qǐng)求超時(shí)問(wèn)題(設(shè)置postman超時(shí)時(shí)間)(接口提供者設(shè)置了nginx超時(shí)時(shí)間)

    https://yma16.inscode.cc/ 查詢別人的一下子就返回了,查詢我自己的,1分鐘還不返回,然后就顯示超時(shí)了。。 一開(kāi)始我還以為是這個(gè)開(kāi)源項(xiàng)目本身的問(wèn)題,設(shè)置了請(qǐng)求超時(shí)時(shí)間,我還給它改了超時(shí)時(shí)間,后來(lái)發(fā)現(xiàn)不是的。。。 本來(lái)是100000的,我給改成1000000了,我對(duì)js代碼不熟,

    2024年02月12日
    瀏覽(93)
  • 微信小程序封裝網(wǎng)絡(luò)請(qǐng)求設(shè)置超時(shí)5min不生效

    背景: 開(kāi)發(fā)微信小程序時(shí),由于有些業(yè)務(wù)場(chǎng)景特殊,接口返回時(shí)間較長(zhǎng),因此使用flyio封裝網(wǎng)絡(luò)請(qǐng)求時(shí)將timeout設(shè)置為5min。 問(wèn)題: 設(shè)置timeout為5min,發(fā)現(xiàn)請(qǐng)求時(shí)長(zhǎng)超過(guò)1min后請(qǐng)求自動(dòng)斷開(kāi)了。 解決方案: 除了在網(wǎng)絡(luò)請(qǐng)求那設(shè)置,還需要在app.json中設(shè)置networkTimeout中的request屬性

    2024年01月17日
    瀏覽(28)
  • Jmeter 設(shè)置全局請(qǐng)求 重點(diǎn)cook

    Jmeter 設(shè)置全局請(qǐng)求 重點(diǎn)cook

    原因 在使用jmeter 過(guò)程中為了方便 ,會(huì)設(shè)置很多公眾信心 比如請(qǐng)求頭? 請(qǐng)求cook 還會(huì)設(shè)置多個(gè)線程組 在同一個(gè)線程組中 我們只需要設(shè)置一個(gè)請(qǐng)求請(qǐng)求cook 就可以了 但是 有逆骨 就是喜歡多個(gè)線程組所以出現(xiàn)問(wèn)題了 解決方案 設(shè)置一個(gè)全局變量 步驟 在測(cè)試計(jì)劃中設(shè)置一個(gè)信息

    2024年01月25日
    瀏覽(20)
  • 解鎖新技能《logback標(biāo)記日志過(guò)濾器MarkerFilter》

    開(kāi)源日志SDK(純java版) 在logback-classic中存在一個(gè)全局過(guò)濾器TurboFilter,TurboFilter是與LoggerContext綁定,會(huì)在會(huì)在其它過(guò)濾器之前執(zhí)行;MarkerFilter是TurboFilter的一個(gè)子類(lèi),其作用是標(biāo)記日志是否記錄入文件之中,可以指定標(biāo)記的日志記錄到文件中;也可以指定標(biāo)記的日志拒絕記錄到

    2024年02月15日
    瀏覽(14)
  • 解鎖新技能《基于logback的純java版本SDK實(shí)現(xiàn)》

    開(kāi)源SDK: 在項(xiàng)目開(kāi)發(fā)過(guò)程中通常會(huì)使用logback作為日志記錄的依賴工具,使用方式是引入logback相關(guān)jar包,然后配置logback.xml配置文件的方式來(lái)實(shí)現(xiàn);xml的配置方案如果是一個(gè)兩個(gè)項(xiàng)目還好,那如果是幾十個(gè)項(xiàng)目呢?每個(gè)項(xiàng)目都要寫(xiě)一遍配置文件也是一鍵很繁瑣的事情,而且配

    2024年02月16日
    瀏覽(18)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包