欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring cloud restTemplate 傳遞復雜參數的方式(多個對象)

 更新時間:2018年05月21日 16:06:23   作者:MatrixCod  
這篇文章主要介紹了Spring cloud restTemplate 傳遞復雜參數的方式(多個對象),需要的朋友可以參考下

使用微服務的時候往往服務之間調用比較麻煩,spring cloud提供了Feign接口調用,RestTemplate調用的方式

這里我探討下RestTemplate調用的方式:

服務A:接收三個對象參數  這三個參數的是通過數據庫查詢出來的

服務B:要調用服務A 服務B提供了查詢三個參數的方法,后面要使用三個參數

對于服務A,處理的方式有兩中

1. 服務B提供一個Feign接口將查詢三個參數的方法公開,服務A直接引用Feign來查詢參數,服務B只需要將三個查詢關鍵字傳遞過去即可

服務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); 
 }

服務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", "保存出現異常"); 
      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", "驗證出現異常"); 
      result.put("message", e.getMessage()); 
      return result; 
    } 
    if(message!=null){ 
      result.put("error", "驗證不通過"); 
      result.put("message", message); 
      return result; 
    } 
    PersistTask persistTask=new PersistTask(); 
    persistTask.init(impId,filePath, busiCode, params,user); 
    result.putAll(ImportQueue.submit(persistTask)); 
    return result; 
  } 

服務B 提供的B-Fegin

@FeignClient(value = "frame-service",path = "/excelApi/v1") 
public interface ExcelFreign extends ExcelApi { 
}

服務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; 
/** 
   * 獲取導入配置項 
   * @param busiCode 
   * @return 
   */ 
  @GetMapping("/getImportConfig/{busicode}") 
  CmdImportConfigDto getCmdImportConfigByBusiCode(@PathVariable("busicode") String busiCode); 
  /** 
   * 保存信息 
   * @param importDto 
   * @return 
   */ 
  @PostMapping("/saveImport") 
  String saveCmdImportDto(@RequestBody CmdImportDto importDto); 
} 

服務B 實現api接口的action

@RestController 
@RequestMapping("/excelApi/v1") 
public class ExcelFeignAction implements ExcelApi { 
@Autowired 
  private CmdExportService exportService; 
 /** 
   * 獲取導入配置項 
   * @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)出現異常"); 
    } 
  } 
}

服務B 調用服務A  action層

/** 
   * 
   * @param busicode 導出的業(yè)務編碼 能確定某個模塊做導出操作 
   * @param values 請求參數 
   * 
   *        通過restTemplate 傳遞復雜參數 
   * @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("參數錯誤,請檢查參數是否正確,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(); 
    // 獲取用戶瀏覽器的種類 對不同的瀏覽器進行編碼處理 
    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.服務B將查詢出來的參數直接傳遞給服務A

服務A:

/** 
   * 接收參數傳遞 
   * 分別接收下面三種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("輸出文件出錯"); 
    } 
  } 

服務B:

/** 
   * 
   * @param busicode 導出的業(yè)務編碼 能確定某個模塊做導出操作 
   * @param values 請求參數 
   * 
   *        通過restTemplate 傳遞復雜參數 
   * @return 
   * 返回 文件流 讓瀏覽器彈出下載 目前需要解決 將字節(jié)流響應到瀏覽器的控制臺了 后面均采用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("參數錯誤,請檢查參數是否正確,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í)行請求調用 
   * @param busiCode 
   * @param variables 
   * @return 
   */ 
   private Map excuteRestTemplate(String busiCode,Map variables){ 
     String serviceId=""; 
     //查詢導出配置 
     CmdExportConfigDto cmdExportConfig = exportService.getCmdExportConfigByBusiCode(busiCode); 
     serviceId = cmdExportConfig.getSystemType(); 
     if(cmdExportConfig==null){ 
       throw new BusinessRuntimeException("沒有導出配置無法導出"); 
     } 
     //根據導出配置id獲取導出字段信息 
     List<CmdExportFieldConfigDto> exportFieldList = exportService.getAllCmdExportFieldConfigDtoByConfigId(cmdExportConfig.getId()); 
     if(StringUtils.isBlank(serviceId)){ 
       throw new BusinessRuntimeException("未配置導出的服務"); 
     } 
     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); 
   } 

設置瀏覽器頭

/** 
   * 根據不同的瀏覽器類型設置下載文件的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; 
  } 

總結

以上所述是小編給大家介紹的Spring cloud restTemplate 傳遞復雜參數的方式(多個對象),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!

相關文章

  • mybatis分頁絕對路徑寫法過程詳解

    mybatis分頁絕對路徑寫法過程詳解

    這篇文章主要介紹了mybatis分頁絕對路徑寫法過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-12-12
  • java.lang.NullPointerException 如何處理空指針異常的實現

    java.lang.NullPointerException 如何處理空指針異常的實現

    這篇文章主要介紹了java.lang.NullPointerException 如何處理空指針異常的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-12-12
  • Java由淺入深學習數組的使用

    Java由淺入深學習數組的使用

    數組對于每一門編程語言來說都是重要的數據結構之一,當然不同語言對數組的實現及處理也不盡相同。Java?語言中提供的數組是用來存儲固定大小的同類型元素
    2022-05-05
  • Java基于WebMagic爬取某豆瓣電影評論的實現

    Java基于WebMagic爬取某豆瓣電影評論的實現

    這篇文章主要介紹了Java基于WebMagic爬取某豆瓣電影評論的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-03-03
  • mybatis多對多查詢的實現(xml方式和注解方式)

    mybatis多對多查詢的實現(xml方式和注解方式)

    本文主要介紹了mybatis多對多查詢的實現,有xml方式和注解方式兩種,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2024-08-08
  • 簡單學習Java+MongoDB

    簡單學習Java+MongoDB

    本文給大家介紹的是如何簡單的使用java+MongoDB實現數據調用的問題,非常的實用,有需要的小伙伴可以參考下
    2016-03-03
  • 超簡單的java獲取鼠標點擊位置坐標的實例(鼠標在Jframe上的坐標)

    超簡單的java獲取鼠標點擊位置坐標的實例(鼠標在Jframe上的坐標)

    在Java窗體Jframe上獲取鼠標點擊的坐標,其中使用了匿名內部類,實例代碼非常簡單易懂,大家可以學習一下
    2018-03-03
  • Java時間戳類Instant的使用詳解

    Java時間戳類Instant的使用詳解

    這篇文章主要為大家詳細介紹了Java中時間戳類Instant的使用方法,文中的示例代碼講解詳細,對我們學習Java有一定幫助,需要的可以參考一下
    2022-09-09
  • Java實現單例模式之餓漢式、懶漢式、枚舉式

    Java實現單例模式之餓漢式、懶漢式、枚舉式

    本篇文章主要介紹了Java實現單例的3種普遍的模式,餓漢式、懶漢式、枚舉式。具有一定的參考價值,感興趣的小伙伴們可以參考一下。
    2016-10-10
  • java數據結構與算法之馬踏棋盤

    java數據結構與算法之馬踏棋盤

    這篇文章主要為大家詳細介紹了java數據結構與算法之馬踏棋盤,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-02-02

最新評論