SpringBoot?Http遠程調(diào)用的方法
本文實例為大家分享了SpringBoot Http遠程調(diào)用的具體代碼,供大家參考,具體內(nèi)容如下
一、在實現(xiàn)遠程調(diào)用時可以使用feign與http遠程調(diào)用,兩者的關(guān)系有一下幾點:
feign、http,有時候在調(diào)用第三方api的時候、使用httpclient,別人的接口不可能提供它的配置,自己項目框架是spring的,使用feign相互配置,都是okhttpclient的方式。Feign是一個接口聲明式調(diào)用框架,實現(xiàn)了一個抽象層的邏輯,沒有真正實現(xiàn)底層http請求,提供了一個client接口用于實現(xiàn)底層http操作,默認提供的實現(xiàn)是基于httpurlconnection,也有基于apachehttpclient的實現(xiàn),且feign具有分布式負載均衡功能。
二、使用案例
需求是在本服務(wù)中調(diào)用另外一個服務(wù)中的設(shè)備上線的功能,有feign、http等可以選擇,這里選擇的是http調(diào)用。
?/** ? ? ?* 超級管理員授權(quán) ? ? ?* @param userName ? ? ?* @param clientid ? ? ?* @return ? ? ?*/ ? ? @PostMapping("/mqtt/superuser") ? ? @Transactional ? ? public Integer loginCheck2(@RequestParam("username") String userName, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? @RequestParam("clientid") String clientid){ ? ? ? ? System.out.println(userName); ? ? ? ? System.out.println("超級管理員"); ? ? ? ? userName = "6217XXXXXXXXXXXd85/3XXXX3"; ? ? ? ? //拼接實體類跳轉(zhuǎn)ibms-iot平臺,上線 ? ? ? ? publishConnected(clientid, userName); ? ? ? ? return 400; ? ? }
/** ? ? ?* 遠程調(diào)用另一個服務(wù)中的設(shè)備上線功能 ? ? ?* @param clientid ? ? ?* @param userName ? ? ?*/ ? ? private void publishConnected(String clientid, String userName) { ? ? ? ? Connected connected = new Connected(); ? ? ? ? connected.setAction(ACTION); ? ? ? ? connected.setClientid(clientid); ? ? ? ? connected.setUsername(userName); ? ? ? ? Date date = new Date(); ? ? ? ? connected.setConnected_at(date.getTime()); ? ? ? ? Map<String, Object> param = BeanUtil.beanToMap(connected, false, true); ? ? ? ? String url = IotPropertiesConfig.HTTP_PREFIX + IotPropertiesConfig.IP_PORT+ UrlConstant.webHook_path; ? ? ? ? String result = HttpUtils.postByRetry(url, param, IotPropertiesConfig.HTTP_TIMEOUT); ? ? ? ? log.info("設(shè)備:{}上線內(nèi)容的通知結(jié)果:{}",connected.getUsername(),result); ? ? }
httpUtil工具類:
package com.setch.crodigy.utils; import cn.hutool.http.HttpRequest; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.rholder.retry.*; import com.google.common.base.Predicates; import lombok.extern.slf4j.Slf4j; import java.util.Map; import java.util.concurrent.*; /** ?* 接口定制工具類 ?*/ @Slf4j public class HttpUtils { ? ? private static final String CONTENT_TYPE = "Content-Type"; ? ? private static final String AUTHORIZATION = "Authorization"; ? ? private static final String CONTENT_TYPE_VALUE = "application/x-www-form-urlencoded"; ? ? private static final String CONTENT_TYPE_VALUE_JSON = "application/json"; ? ? private static ObjectMapper json = new ObjectMapper(); ? ? private static ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); ? ? //重試間隔 ? ? private static long sleepTime = 1L; ? ? //重試次數(shù) ? ? private static int attemptNumber = 5; ? ? //設(shè)置重試機制 ? ? private final static Retryer<String> retryer = RetryerBuilder.<String>newBuilder() ? ? ? ? ? ? .retryIfResult(Predicates.<String>isNull()) ? ?// 設(shè)置自定義段元重試源 ? ? ? ? ? ? .retryIfExceptionOfType(Exception.class) ? ? ? ?// 設(shè)置異常重試源 ? ? ? ? ? ? .retryIfRuntimeException() ? ? ? ? ? ? ? ? ? ? ?// 設(shè)置異常重試源 ? ? ? ? ? ? .withStopStrategy(StopStrategies.stopAfterAttempt(attemptNumber)) ? // 設(shè)置重試次數(shù) ? ?設(shè)置重試超時時間???? ? ? ? ? ? ? .withWaitStrategy(WaitStrategies.fixedWait(sleepTime, TimeUnit.SECONDS)) // 設(shè)置每次重試間隔 ? ? ? ? ? ? .build(); ? ? /** ? ? ?* 設(shè)備上線使用 ? ? ?* @param url ? ? ?* @param paramMap ? ? ?* @param timeout ? ? ?*/ ? ? public static void deviceOnline(String url, Map<String, Object> paramMap, int timeout) { ? ? ? ? cachedThreadPool.execute(new Runnable() { ? ? ? ? ? ? @Override ? ? ? ? ? ? public void run() { ? ? ? ? ? ? ? ? ?postByRetry("",null,1); ? ? ? ? ? ? } ? ? ? ? }); ? ? } ? ? /** ? ? ?* ? ? ?* @param url 訪問路徑 ? ? ?* @param paramMap 請求體 ? ? ?* @param timeout 超時時間 ?單位: 秒 ? ? ?* @return ? ? ?* @throws JsonProcessingException ? ? ?*/ ? ? public static String postByRetry(String url, Map<String, Object> paramMap, int timeout) { ? ? ? ? Callable<String> task = new Callable<String>() { ? ? ? ? ? ? int i = 0; ? ? ? ? ? ? @Override ? ? ? ? ? ? public String call() throws Exception { ? ? ? ? ? ? ? ? i++; ? ? ? ? ? ? ? ? if(i > 1){ ? ? ? ? ? ? ? ? ? ? log.info("請求初次執(zhí)行失敗,開始第{}次執(zhí)行!", i); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? String result = post(url, paramMap, timeout); ? ? ? ? ? ? ? ? return result; ? ? ? ? ? ? } ? ? ? ? }; ? ? ? ? String res = ""; ? ? ? ? try { ? ? ? ? ? ? //執(zhí)行任務(wù)的重試,得到返回結(jié)果 ? ? ? ? ? ? ?res = retryer.call(task); ? ? ? ? } catch (ExecutionException e) { ? ? ? ? ? ? log.error("Post ExecutionException", e); ? ? ? ? } catch (RetryException e) { ? ? ? ? ? ? log.error("Post RetryException", e); ? ? ? ? } ? ? ? ? return res; ? ? } ? ? /** ? ? ?* ? ? ?* @param url 訪問路徑 ? ? ?* @param paramMap 請求體 ? ? ?* @param timeout 超時時間 ?單位: 秒 ? ? ?* @return ? ? ?* @throws JsonProcessingException ? ? ?*/ ? ? public static String post(String url, Map<String, Object> paramMap, int timeout) throws JsonProcessingException { ? ? ? ? String map = json.writeValueAsString(paramMap); ? ? ? ? String result = HttpRequest ? ? ? ? ? ? ? ? .post(url).header(CONTENT_TYPE,CONTENT_TYPE_VALUE).timeout(timeout * 1000) ? ? ? ? ? ? ? ? .body(map).execute().body(); ? ? ? ? return result; ? ? } ? ? /** ? ? ?* ? ? ?* @param url 訪問路徑 ? ? ?* @param map 請求體 ? ? ?* @param timeout 超時時間 ?單位: 秒 ? ? ?* @return ? ? ?*/ ? ? public static String post(String url, String map, int timeout) ?{ ? ? ? ? String result = HttpRequest ? ? ? ? ? ? ? ? .post(url).header(CONTENT_TYPE,CONTENT_TYPE_VALUE).timeout(timeout * 1000) ? ? ? ? ? ? ? ? .body(map).execute().body(); ? ? ? ? return result; ? ? } ? ? /** ? ? ?* ? ? ?* @param url 訪問路徑 ? ? ?* @param map 請求體 ? ? ?* @param timeout 超時時間 ?單位: 秒 ? ? ?* @return ? ? ?*/ ? ? public static String post(String url, String map, int timeout,String authorization) ?{ ? ? ? ? String result = HttpRequest ? ? ? ? ? ? ? ? .post(url).header(CONTENT_TYPE,CONTENT_TYPE_VALUE).header(AUTHORIZATION,authorization) ? ? ? ? ? ? ? ? ? ? ? ? .timeout(timeout * 1000) ? ? ? ? ? ? ? ? .body(map).execute().body(); ? ? ? ? return result; ? ? } ? ? /** ? ? ?* ? ? ?* @param url 訪問路徑 ? ? ?* @param timeout 超時時間 ?單位: 秒 ? ? ?* @param authorization 認證token ? ? ?*/ ? ? public static String get(String url, int timeout,String authorization) ?{ ? ? ? ? String result = HttpRequest.get(url).header(CONTENT_TYPE,CONTENT_TYPE_VALUE_JSON).header(AUTHORIZATION,authorization) ? ? ? ? ? ? ? ? .timeout(timeout * 1000).execute().body(); ? ? ? ? return result; ? ? } ? ? /** ? ? ?* ? ? ?* @param url 訪問路徑 ? ? ?* @param timeout 超時時間 ?單位: 秒 ? ? ?* @param authorization 認證token ? ? ?*/ ? ? public static String delete(String url, int timeout,String authorization ,String map) ?{ ? ? ? ? String result = HttpRequest.delete(url).header(CONTENT_TYPE,CONTENT_TYPE_VALUE_JSON).header(AUTHORIZATION,authorization) ? ? ? ? ? ? ? ? .timeout(timeout * 1000).body(map).execute().body(); ? ? ? ? return result; ? ? } ? ? /** ? ? ?* ? ? ?* @param url 訪問路徑 ? ? ?* @param timeout 超時時間 ?單位: 秒 ? ? ?* @param authorization 認證token ? ? ?*/ ? ? public static String delete(String url, int timeout,String authorization ) ?{ ? ? ? ? String result = HttpRequest.delete(url).header(CONTENT_TYPE,CONTENT_TYPE_VALUE_JSON).header(AUTHORIZATION,authorization) ? ? ? ? ? ? ? ? .timeout(timeout * 1000).execute().body(); ? ? ? ? return result; ? ? } }
這里的publishConnectEd(clientid,userName);使用http遠程調(diào)用另外一個服務(wù)中的設(shè)備上線的接口。
String url : 需要跳轉(zhuǎn)的接口路徑。(如:http://localhost:8080/user/login)
param: 遠程調(diào)用時,所需參數(shù)。
HttpUtils.postByRetry() 實現(xiàn)http遠程調(diào)用。
下面是需要被遠程調(diào)用的接口
import antlr.StringUtils; import com.setch.crodigy.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import java.util.List; @RequestMapping("/testDemo") @RestController public class ProductController { ? ? @Autowired ? ? private ProductService productService; ? ? @PostMapping("/save") ? ? @Transactional ? ? public boolean saveProduct(@RequestBody Product product){ ? ? ? ? Product result = productService.save(product); ? ? ? ? if (result != null){ ? ? ? ? ? ? return true; ? ? ? ? }else { ? ? ? ? ? ? return false; ? ? ? ? } ? ? } }
以上是本人個人使用案例,測試成功,初次使用,若有問題歡迎大家提出指正。
希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java+mysql實現(xiàn)學(xué)籍管理系統(tǒng)
這篇文章主要為大家詳細介紹了Java+mysql實現(xiàn)學(xué)籍管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-07-07使用mybatis-plus報錯Invalid bound statement (not found)錯誤
這篇文章主要介紹了使用mybatis-plus報錯Invalid bound statement (not found)錯誤,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09SpringBoot整合Mybatis-Plus、Jwt實現(xiàn)登錄token設(shè)置
Spring Boot整合Mybatis-plus實現(xiàn)登錄常常需要使用JWT來生成用戶的token并設(shè)置用戶權(quán)限的攔截器,本文就來詳細的介紹一下,具有一定的參考價值,感興趣的可以了解一下2024-02-02RestFul風(fēng)格 — 使用@PathVariable傳遞參數(shù)報錯404的解決
這篇文章主要介紹了RestFul風(fēng)格 — 使用@PathVariable傳遞參數(shù)報錯404的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10