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

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

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

使用微服務(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ù)查詢出來(lái)的

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

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

1. 服務(wù)B提供一個(gè)Feign接口將查詢?nèi)齻€(gè)參數(shù)的方法公開(kāi),服務(wù)A直接引用Feign來(lái)查詢參數(shù),服務(wù)B只需要將三個(gè)查詢關(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(); 
    // 獲取用戶瀏覽器的種類 對(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將查詢出來(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=""; 
     //查詢導(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ù)不同的瀏覽器類型設(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ì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論