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;
? ? ? ? }
? ? }
}以上是本人個人使用案例,測試成功,初次使用,若有問題歡迎大家提出指正。
希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java中OAuth2.0第三方授權(quán)原理與實戰(zhàn)
本文主要介紹了Java中OAuth2.0第三方授權(quán)原理與實戰(zhàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-05-05
java對象轉(zhuǎn)成byte數(shù)組的3種方法
這篇文章主要為大家詳細介紹了java對象轉(zhuǎn)成byte數(shù)組的3種方法,具有一定的參考價值,感興趣的朋友可以參考一下2018-06-06
Struts2學習筆記(3)-DMI動態(tài)調(diào)用方式
本文主要介紹Struts2的DMI動態(tài)調(diào)用的兩種方式,簡單實用,希望能給大家做一個參考。2016-06-06

