SpringBoot?Http遠(yuǎn)程調(diào)用的方法
本文實(shí)例為大家分享了SpringBoot Http遠(yuǎn)程調(diào)用的具體代碼,供大家參考,具體內(nèi)容如下
一、在實(shí)現(xiàn)遠(yuǎn)程調(diào)用時(shí)可以使用feign與http遠(yuǎn)程調(diào)用,兩者的關(guān)系有一下幾點(diǎn):
feign、http,有時(shí)候在調(diào)用第三方api的時(shí)候、使用httpclient,別人的接口不可能提供它的配置,自己項(xiàng)目框架是spring的,使用feign相互配置,都是okhttpclient的方式。Feign是一個(gè)接口聲明式調(diào)用框架,實(shí)現(xiàn)了一個(gè)抽象層的邏輯,沒有真正實(shí)現(xiàn)底層http請(qǐng)求,提供了一個(gè)client接口用于實(shí)現(xiàn)底層http操作,默認(rèn)提供的實(shí)現(xiàn)是基于httpurlconnection,也有基于apachehttpclient的實(shí)現(xiàn),且feign具有分布式負(fù)載均衡功能。
二、使用案例
需求是在本服務(wù)中調(diào)用另外一個(gè)服務(wù)中的設(shè)備上線的功能,有feign、http等可以選擇,這里選擇的是http調(diào)用。
?/**
? ? ?* 超級(jí)管理員授權(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("超級(jí)管理員");
? ? ? ? userName = "6217XXXXXXXXXXXd85/3XXXX3";
? ? ? ? //拼接實(shí)體類跳轉(zhuǎn)ibms-iot平臺(tái),上線
? ? ? ? publishConnected(clientid, userName);
? ? ? ? return 400;
? ? }/**
? ? ?* 遠(yuǎn)程調(diào)用另一個(gè)服務(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è)置重試機(jī)制
? ? 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è)置重試超時(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 請(qǐng)求體
? ? ?* @param timeout 超時(shí)時(shí)間 ?單位: 秒
? ? ?* @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("請(qǐng)求初次執(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 請(qǐng)求體
? ? ?* @param timeout 超時(shí)時(shí)間 ?單位: 秒
? ? ?* @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 請(qǐng)求體
? ? ?* @param timeout 超時(shí)時(shí)間 ?單位: 秒
? ? ?* @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 請(qǐng)求體
? ? ?* @param timeout 超時(shí)時(shí)間 ?單位: 秒
? ? ?* @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 超時(shí)時(shí)間 ?單位: 秒
? ? ?* @param authorization 認(rèn)證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 超時(shí)時(shí)間 ?單位: 秒
? ? ?* @param authorization 認(rèn)證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 超時(shí)時(shí)間 ?單位: 秒
? ? ?* @param authorization 認(rèn)證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遠(yuǎn)程調(diào)用另外一個(gè)服務(wù)中的設(shè)備上線的接口。
String url : 需要跳轉(zhuǎn)的接口路徑。(如:http://localhost:8080/user/login)
param: 遠(yuǎn)程調(diào)用時(shí),所需參數(shù)。
HttpUtils.postByRetry() 實(shí)現(xiàn)http遠(yuǎn)程調(diào)用。
下面是需要被遠(yuǎn)程調(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;
? ? ? ? }
? ? }
}以上是本人個(gè)人使用案例,測(cè)試成功,初次使用,若有問題歡迎大家提出指正。
希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- springBoot使用openfeign來遠(yuǎn)程調(diào)用的實(shí)現(xiàn)
- 在SpringBoot中,如何使用Netty實(shí)現(xiàn)遠(yuǎn)程調(diào)用方法總結(jié)
- SpringBoot整合Dubbo框架,實(shí)現(xiàn)RPC服務(wù)遠(yuǎn)程調(diào)用
- SpringBoot使用Netty實(shí)現(xiàn)遠(yuǎn)程調(diào)用的示例
- SpringBoot2.0 整合 Dubbo框架實(shí)現(xiàn)RPC服務(wù)遠(yuǎn)程調(diào)用方法
- HttpClient實(shí)現(xiàn)遠(yuǎn)程調(diào)用
相關(guān)文章
springboot實(shí)現(xiàn)多文件上傳功能
這篇文章主要為大家詳細(xì)介紹了springboot實(shí)現(xiàn)多文件上傳功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-11-11
Java中OAuth2.0第三方授權(quán)原理與實(shí)戰(zhàn)
本文主要介紹了Java中OAuth2.0第三方授權(quán)原理與實(shí)戰(zhàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05
java對(duì)象轉(zhuǎn)成byte數(shù)組的3種方法
這篇文章主要為大家詳細(xì)介紹了java對(duì)象轉(zhuǎn)成byte數(shù)組的3種方法,具有一定的參考價(jià)值,感興趣的朋友可以參考一下2018-06-06
Struts2學(xué)習(xí)筆記(3)-DMI動(dòng)態(tài)調(diào)用方式
本文主要介紹Struts2的DMI動(dòng)態(tài)調(diào)用的兩種方式,簡(jiǎn)單實(shí)用,希望能給大家做一個(gè)參考。2016-06-06

