您好,登錄后才能下訂單哦!
這篇文章主要介紹了Springcloud中restTemplate如何傳遞復(fù)雜參數(shù),具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
使用微服務(wù)的時(shí)候往往服務(wù)之間調(diào)用比較麻煩,spring cloud提供了Feign接口調(diào)用,RestTemplate調(diào)用的方式
這里我探討下RestTemplate調(diào)用的方式:
服務(wù)A:接收三個(gè)對象參數(shù) 這三個(gè)參數(shù)的是通過數(shù)據(jù)庫查詢出來的
服務(wù)B:要調(diào)用服務(wù)A 服務(wù)B提供了查詢?nèi)齻€(gè)參數(shù)的方法,后面要使用三個(gè)參數(shù)
對于服務(wù)A,處理的方式有兩中
1. 服務(wù)B提供一個(gè)Feign接口將查詢?nèi)齻€(gè)參數(shù)的方法公開,服務(wù)A直接引用Feign來查詢參數(shù),服務(wù)B只需要將三個(gè)查詢關(guān)鍵字傳遞過去即可
服務(wù)A action
@PostMapping("/import/{busiCode}/{filePath}") public Map<String,String> importExcel(@PathVariable("filePath") String filePath,@PathVariable("busiCode") String busiCode,@RequestBody Map<String, String> params, HttpServletRequest request,HttpServletResponse response) { response.setCharacterEncoding("UTF-8"); UserInfo user = UserUtil.getUser(); return excelService.importExcel(filePath,busiCode,params,user); }
服務(wù)A service
//引入Feign接口 private ExcelFreign excelFreign; public Map<String,String> importExcel(String filePath, String busiCode,Map<String, String> params,UserInfo user ) { Map<String,String> result=new HashMap<String,String>(); excelFreign = SpringTool.getApplicationContext().getBean(ExcelFreign.class); CmdImportConfigDto configDto = excelFreign.getCmdImportConfigByBusiCode(busiCode); CmdImportDto importDto=new CmdImportDto(); importDto.setImportConfigId(configDto.getId()); importDto.setExcelPath(filePath); importDto.setParam(new GsonBuilder().create().toJson(params)); importDto.setLog(""); Long impId=null; try { impId= Long.valueOf(excelFreign.saveCmdImportDto(importDto)); } catch (Exception e1) { e1.printStackTrace(); result.put("error", "保存出現(xiàn)異常"); result.put("message", e1.getMessage()); return result; } try{ excelFreign.updateImportStatus(impId, ImportConstant.ImportStatus.SUBMIT, "提交成功"); }catch(Exception e){ e.printStackTrace(); } ValidateTask validateTask=new ValidateTask(); validateTask.init(impId,filePath, busiCode, params,user); String message; try { message = validateTask.call(); } catch (Exception e) { e.printStackTrace(); result.put("error", "驗(yàn)證出現(xiàn)異常"); result.put("message", e.getMessage()); return result; } if(message!=null){ result.put("error", "驗(yàn)證不通過"); result.put("message", message); return result; } PersistTask persistTask=new PersistTask(); persistTask.init(impId,filePath, busiCode, params,user); result.putAll(ImportQueue.submit(persistTask)); return result; }
服務(wù)B 提供的B-Fegin
@FeignClient(value = "frame-service",path = "/excelApi/v1") public interface ExcelFreign extends ExcelApi { }
服務(wù)B api層 B-api
public interface ExcelApi { /** * 更新狀態(tài) * @param impId * @param importType * @param result */ @PostMapping("/updateImportStatus/{impId}/{importType}/{result}") void updateImportStatus(@PathVariable("impId") Long impId, @PathVariable("importType") String importType, @PathVariable("result") String result) throws Exception; /** * 獲取導(dǎo)入配置項(xiàng) * @param busiCode * @return */ @GetMapping("/getImportConfig/{busicode}") CmdImportConfigDto getCmdImportConfigByBusiCode(@PathVariable("busicode") String busiCode); /** * 保存信息 * @param importDto * @return */ @PostMapping("/saveImport") String saveCmdImportDto(@RequestBody CmdImportDto importDto); }
服務(wù)B 實(shí)現(xiàn)api接口的action
@RestController @RequestMapping("/excelApi/v1") public class ExcelFeignAction implements ExcelApi { @Autowired private CmdExportService exportService; /** * 獲取導(dǎo)入配置項(xiàng) * @param busiCode * @return */ @GetMapping("/getImportConfig/{busicode}") public CmdImportConfigDto getCmdImportConfigByBusiCode(@PathVariable("busicode") String busiCode){ return cmdImportConfigService.getCmdImportConfigByBusiCode(busiCode); } /** * 更新狀態(tài) * @param impId * @param importStatus * @param result */ @PostMapping("/updateImportStatus/{impId}/{importType}/{result}") public void updateImportStatus(@PathVariable("impId") Long impId, @PathVariable("importType") String importStatus, @PathVariable("result") String result) throws Exception{ cmdImportService.updateImportStatus(impId,importStatus,new Date() , result); } /** * 保存信息 * @param importDto * @return */ @PostMapping("/saveImport") public String saveCmdImportDto(@RequestBody CmdImportDto importDto){ try{ cmdImportService.saveCmdImportDto(importDto); return importDto.getId(); }catch (Exception e){ e.printStackTrace(); throw new BusinessRuntimeException("系統(tǒng)出現(xiàn)異常"); } } }
服務(wù)B 調(diào)用服務(wù)A action層
/** * * @param busicode 導(dǎo)出的業(yè)務(wù)編碼 能確定某個(gè)模塊做導(dǎo)出操作 * @param values 請求參數(shù) * * 通過restTemplate 傳遞復(fù)雜參數(shù) * @return * 返回 文件流 讓瀏覽器彈出下載 */ @PostMapping(value = "/export/v3/{busicode}") @ResponseBody public ResponseEntity<byte[]> expDownLoadV3(@PathVariable("busicode") String busicode , @RequestBody Map<String,Object> values, HttpServletRequest request)throws Exception { if(StringUtils.isBlank(busicode)){ throw new BusinessRuntimeException("參數(shù)錯(cuò)誤,請檢查參數(shù)是否正確,busicode ?"); } // 獲取執(zhí)行過程 Map map = restTemplate.postForObject("http://" + serviceId + "/excelApi/v1/文件名"/"+busicode,values,Map.class); String path = (String)map.get("filepath"); byte[] excel = FastDFSClient.downloadToBytes(path); CmdExportConfigDto cmdExportConfig = exportService.getCmdExportConfigByBusiCode(busicode); //獲取文件名 String fileName = cmdExportConfig.getReportName(); // 獲取文件后綴名 String extFileName = path.substring(path.lastIndexOf('.')+1); HttpHeaders headers = new HttpHeaders(); // 獲取用戶瀏覽器的種類 對不同的瀏覽器進(jìn)行編碼處理 final String userAgent = request.getHeader("USER-AGENT"); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", FrameUrlConstants.transFromFileName(userAgent,fileName) + "." + extFileName); return new ResponseEntity<byte[]>(excel,headers,HttpStatus.OK); }
2.服務(wù)B將查詢出來的參數(shù)直接傳遞給服務(wù)A
服務(wù)A:
/** * 接收參數(shù)傳遞 * 分別接收下面三種key value的鍵值對 * cmdExportConfig:CmdExportConfigDto * exportFieldList:List<CmdExportFieldConfigDto> * params:Map * @param params * @param request * @param response * @return */ @PostMapping("/export/v2") public ResponseEntity exportExcel(@RequestBody Map<String,Object> params,HttpServletRequest request,HttpServletResponse response) { response.setCharacterEncoding("UTF-8"); try { // 將文件的路徑獲取到 ObjectMapper mapper = new ObjectMapper(); LinkedHashMap requestParMap = (LinkedHashMap)params.get("cmdExportConfig"); CmdExportConfigDto cmdExportConfigDto = null; List<CmdExportFieldConfigDto> exportFieldList = null; if(requestParMap.size()>0){ cmdExportConfigDto = mapper.convertValue(requestParMap,CmdExportConfigDto.class); } ArrayList arrayList = (ArrayList)params.get("exportFieldList"); if(arrayList.size()>0){ exportFieldList = mapper.convertValue(arrayList, new TypeReference<CmdExportFieldConfigDto>() {}); } Map values = (Map)params.get("params"); String filePath = excelService.exportExcel(cmdExportConfigDto,exportFieldList,params,request.getServletContext().getRealPath("/")); Map<String,String> map = new HashMap<String, String>(); map.put("filepath", filePath); return new ResponseEntity(map,HttpStatus.OK); }catch (IOException e){ throw new RuntimeException("輸出文件出錯(cuò)"); } }
服務(wù)B:
/** * * @param busicode 導(dǎo)出的業(yè)務(wù)編碼 能確定某個(gè)模塊做導(dǎo)出操作 * @param values 請求參數(shù) * * 通過restTemplate 傳遞復(fù)雜參數(shù) * @return * 返回 文件流 讓瀏覽器彈出下載 目前需要解決 將字節(jié)流響應(yīng)到瀏覽器的控制臺了 后面均采用url下載的方式 */ @PostMapping(value = "/export/v3/{busicode}",produces = MediaType.TEXT_PLAIN_VALUE) @ResponseBody public ResponseEntity<byte[]> expDownLoadV3(@PathVariable("busicode") String busicode , @RequestBody Map<String,Object> values, HttpServletRequest request)throws Exception { String busiCode = values.get("busiCode").toString(); if(StringUtils.isBlank(busiCode)){ throw new BusinessRuntimeException("參數(shù)錯(cuò)誤,請檢查參數(shù)是否正確,busiCode ?"); } // 獲取執(zhí)行過程 Map map = excuteRestTemplate(busiCode,values); String path = (String)map.get("filepath"); byte[] excel = FastDFSClient.downloadToBytes(path); CmdExportConfigDto cmdExportConfig = exportService.getCmdExportConfigByBusiCode(busiCode); //獲取文件名 String fileName = cmdExportConfig.getReportName(); // 獲取文件后綴名 String extFileName = path.substring(path.lastIndexOf('.')+1); HttpHeaders headers = new HttpHeaders();erAgent = request.getHeader("USER-AGENT"); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", FrameUrlConstants.transFromFileName(userAgent,fileName) + "." + extFileName); return new ResponseEntity<byte[]>(excel,headers,HttpStatus.OK); } /** * 執(zhí)行請求調(diào)用 * @param busiCode * @param variables * @return */ private Map excuteRestTemplate(String busiCode,Map variables){ String serviceId=""; //查詢導(dǎo)出配置 CmdExportConfigDto cmdExportConfig = exportService.getCmdExportConfigByBusiCode(busiCode); serviceId = cmdExportConfig.getSystemType(); if(cmdExportConfig==null){ throw new BusinessRuntimeException("沒有導(dǎo)出配置無法導(dǎo)出"); } //根據(jù)導(dǎo)出配置id獲取導(dǎo)出字段信息 List<CmdExportFieldConfigDto> exportFieldList = exportService.getAllCmdExportFieldConfigDtoByConfigId(cmdExportConfig.getId()); if(StringUtils.isBlank(serviceId)){ throw new BusinessRuntimeException("未配置導(dǎo)出的服務(wù)"); } Map<String, Object> uriVariables = new HashMap<>(); uriVariables.put("cmdExportConfig",cmdExportConfig); uriVariables.put("exportFieldList",exportFieldList); uriVariables.put("params",variables); return restTemplate.postForObject("http://" + serviceId + "/excelService/export/v2",new HttpEntity(uriVariables),Map.class); }
設(shè)置瀏覽器頭
/** * 根據(jù)不同的瀏覽器類型設(shè)置下載文件的URL編碼 * @param userAgent * @param fileName * @return * @throws Exception */ public static String transFromFileName(String userAgent,String fileName) throws Exception{ String finalFileName = ""; if(StringUtils.contains(userAgent, "MSIE")){//IE瀏覽器 finalFileName = URLEncoder.encode(fileName,"UTF-8"); }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐瀏覽器 finalFileName = new String(fileName.getBytes("GBK"), "ISO8859-1"); }else{ finalFileName = URLEncoder.encode(fileName,"UTF-8");//其他瀏覽器 } return finalFileName; }
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Springcloud中restTemplate如何傳遞復(fù)雜參數(shù)”這篇文章對大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。