麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁(yè) > 開(kāi)發(fā) > Java > 正文

Spring cloud restTemplate 傳遞復(fù)雜參數(shù)的方式(多個(gè)對(duì)象)

2024-07-14 08:40:58
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

使用微服務(wù)的時(shí)候往往服務(wù)之間調(diào)用比較麻煩,spring cloud提供了Feign接口調(diào)用,RestTemplate調(diào)用的方式

這里我探討下RestTemplate調(diào)用的方式:

服務(wù)A:接收三個(gè)對(duì)象參數(shù)  這三個(gè)參數(shù)的是通過(guò)數(shù)據(jù)庫(kù)查詢(xún)出來(lái)的

服務(wù)B:要調(diào)用服務(wù)A 服務(wù)B提供了查詢(xún)?nèi)齻€(gè)參數(shù)的方法,后面要使用三個(gè)參數(shù)

對(duì)于服務(wù)A,處理的方式有兩中

1. 服務(wù)B提供一個(gè)Feign接口將查詢(xún)?nèi)齻€(gè)參數(shù)的方法公開(kāi),服務(wù)A直接引用Feign來(lái)查詢(xún)參數(shù),服務(wù)B只需要將三個(gè)查詢(xún)關(guān)鍵字傳遞過(guò)去即可

服務(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)證不通過(guò)");       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īng)顟B(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īng)顟B(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 請(qǐng)求參數(shù)    *    *        通過(guò)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ò)誤,請(qǐng)檢查參數(shù)是否正確,busicode ?");     }     // 獲取執(zhí)行過(guò)程     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();     // 獲取用戶(hù)瀏覽器的種類(lèi) 對(duì)不同的瀏覽器進(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將查詢(xún)出來(lái)的參數(shù)直接傳遞給服務(wù)A

服務(wù)A:

/**    * 接收參數(shù)傳遞    * 分別接收下面三種key value的鍵值對(duì)    * 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 請(qǐng)求參數(shù)    *    *        通過(guò)restTemplate 傳遞復(fù)雜參數(shù)    * @return    * 返回 文件流 讓瀏覽器彈出下載 目前需要解決 將字節(jié)流響應(yīng)到瀏覽器的控制臺(tái)了 后面均采用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ò)誤,請(qǐng)檢查參數(shù)是否正確,busiCode ?");     }     // 獲取執(zhí)行過(guò)程     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í)行請(qǐng)求調(diào)用    * @param busiCode    * @param variables    * @return    */    private Map excuteRestTemplate(String busiCode,Map variables){      String serviceId="";      //查詢(xún)導(dǎo)出配置      CmdExportConfigDto cmdExportConfig = exportService.getCmdExportConfigByBusiCode(busiCode);      serviceId = cmdExportConfig.getSystemType();      if(cmdExportConfig==null){        throw new BusinessRuntimeException("沒(méi)有導(dǎo)出配置無(wú)法導(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ù)不同的瀏覽器類(lèi)型設(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;   } 

總結(jié)

以上所述是小編給大家介紹的Spring cloud restTemplate 傳遞復(fù)雜參數(shù)的方式(多個(gè)對(duì)象),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)VeVb武林網(wǎng)網(wǎng)站的支持!


注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到JAVA教程頻道。
發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 特大黑人videos与另类娇小 | 欧美综合在线观看视频 | 国产1区在线观看 | 天天夜天天操 | 一区二区三区小视频 | 国产毛片自拍 | 在线看免费观看日本 | 深夜影院一级毛片 | 永久免费黄色大片 | 2019中文字幕在线播放 | 日韩欧美精品电影 | 成人午夜精品久久久久久久3d | 91成人午夜性a一级毛片 | 天天都色视频 | 精品国产乱码久久久久久久久 | 精品一区二区三区免费毛片 | 亚洲福利在线观看视频 | 伦一区二区三区中文字幕v亚洲 | 欧美一级aa免费毛片 | 欧美一级黄色片在线观看 | 中文字幕国产一区 | 亚洲国产精品久久久久久久久久久 | 色97在线 | 国产一区二区视频在线播放 | 国产1区在线 | 国产精品久久久久久影视 | 黄色免费不卡视频 | 性盈盈盈影院 | 成人免费观看在线 | 国产资源在线看 | 一级做受毛片免费大片 | 日本中文字幕电影在线观看 | 精品亚洲午夜久久久久91 | 中国hd高清xxxxvideo | 暴力强行进如hdxxx | 欧美成人精品一区二区男人小说 | 欧洲精品色| 天天操天天碰 | 亚洲国产资源 | 欧美不卡 | 在线播放中文 |