一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Spring cloud restTemplate 傳遞復雜參數的方式(多個對象)

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

2021-05-04 11:43MatrixCod Java教程

這篇文章主要介紹了Spring cloud restTemplate 傳遞復雜參數的方式(多個對象),需要的朋友可以參考下

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

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

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

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

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

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

服務A action

?
1
2
3
4
5
6
7
@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 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//引入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

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

服務B api層 B-api

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public interface ExcelApi {
/**
   * 更新狀態
   * @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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
@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);
  }
 /**
   * 更新狀態
   * @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("系統出現異常");
    }
  }
}

服務B 調用服務A  action層

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
   *
   * @param busicode 導出的業務編碼 能確定某個模塊做導出操作
   * @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 ?");
    }
    // 獲取執行過程
    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:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
   * 接收參數傳遞
   * 分別接收下面三種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:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
   *
   * @param busicode 導出的業務編碼 能確定某個模塊做導出操作
   * @param values 請求參數
   *
   *        通過restTemplate 傳遞復雜參數
   * @return
   * 返回 文件流 讓瀏覽器彈出下載 目前需要解決 將字節流響應到瀏覽器的控制臺了 后面均采用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 ?");
    }
    // 獲取執行過程
    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);
  }
  /**
   * 執行請求調用
   * @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);
   }

設置瀏覽器頭

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
   * 根據不同的瀏覽器類型設置下載文件的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 傳遞復雜參數的方式(多個對象),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!

原文鏈接:https://blog.csdn.net/u010920327/article/details/80042276

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 猫咪色网 | 久久免费资源福利资源站 | 岛国不卡 | 久久全国免费久久青青小草 | 国产一区二区免费视频 | 欧美精品亚洲精品日韩专区va | 视频亚洲一区 | 香蕉草莓视频 | 欧美les同性videos| 亚洲欧美日韩综合在线 | 男人的私人影院 | 免费一级欧美片在线观免看 | 久久久久久久伊人电影 | 99在线视频免费 | 国产精品免费久久久久影院小说 | 91啦在线视频 | 成人福利免费视频 | 日本动漫黄网站在线观看 | 色成人综合网 | 成年人视频免费在线观看 | 亚洲天堂精品在线 | 强插美女| 亚洲欧美激情日韩在线 | 99精品视频一区在线观看miya | 亚洲2023无矿砖码砖区 | 精品一区二区免费视频蜜桃网 | 出轨同学会2在线观看 | 午夜福利合集1000在线 | 毛片群| 国产精品免费看久久久香蕉 | 成人啪精品视频免费网站 | 亚洲第一色网 | juliaann大战两个黑人 | 国产欧美日韩精品在线 | 久久国产精品免费网站 | 日韩高清成人毛片不卡 | 国产精品视频播放 | 视频一区二区国产无限在线观看 | 欧美综合在线 | 情侣宾馆愉拍自拍视频 | 天天天做天天天天爱天天想 |