When using microservices, you often have trouble calling between services. Spring cloud provides Feign interface calls and RestTemplate calls.
Here I will discuss the method of RestTemplate calling:
Service A: The three object parameters that receive these three parameters are queryed through the database.
Service B: To call Service A Service B provides a method to query three parameters, and three parameters must be used later.
For Service A, there are two ways to deal with it
1. Service B provides a Feign interface to disclose the method of querying three parameters. Service A directly references Feign to query parameters. Service B only needs to pass the three query keywords in the past.
Service 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); } Service A service
//Introduce the Feign interface 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", "Exception occurred while saving"); result.put("message", e1.getMessage()); return result; } try{ excelFreign.updateImportStatus(impId, ImportConstant.ImportStatus.SUBMIT, "Submit successful"); } 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", "Exception occurred in verification"); result.put("message", e.getMessage()); return result; } if(message!=null){ result.put("error", "Verification failed"); 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-Fegin provided by Service B
@FeignClient(value = "frame-service",path = "/excelApi/v1") public interface ExcelFreign extends ExcelApi { }Serving B api layer B-api
public interface ExcelApi { /** * Update status* @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; /** * Get import configuration items* @param busiCode * @return */ @GetMapping("/getImportConfig/{busicode}") CmdImportConfigDto getCmdImportConfigByBusiCode(@PathVariable("busicode") String busiCode); /** * Save information* @param importDto * @return */ @PostMapping("/saveImport") String saveCmdImportDto(@RequestBody CmdImportDto importDto); }Service B implements the action of API interface
@RestController @RequestMapping("/excelApi/v1") public class ExcelFeignAction implements ExcelApi { @Autowired private CmdExportService exportService; /** * Get import configuration items* @param busiCode * @return */ @GetMapping("/getImportConfig/{busicode}") public CmdImportConfigDto getCmdImportConfigByBusiCode(@PathVariable("busicode") String busiCode){ return cmdImportConfigService.getCmdImportConfigByBusiCode(busiCode); } /** * Update status* @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); } /** * Save information* @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("System exception"); } } }Service B Calls Service A action layer
/** * * * @param busicode The exported business encoding can determine that a module can export it* @param values Request parameters* * Pass complex parameters through restTemplate* Return the file stream and let the browser pop up to download*/ @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("Parameter is incorrect, please check whether the parameters are correct,busicode ?"); } // Get the execution process Map map = restTemplate.postForObject("http://" + serviceId + "/excelApi/v1/filename"/"+busicode,values,Map.class); String path = (String)map.get("filepath"); byte[] excel = FastDFSClient.downloadToBytes(path); CmdExportConfigDto cmdExportConfig = exportService.getCmdExportConfigByBusiCode(busicode); //Get the file name String fileName = cmdExportConfig.getReportName(); //Get the file suffix name String extFileName = path.substring(path.lastIndexOf('.')+1); HttpHeaders headers = new HttpHeaders(); //Get the type of user browser encoding different browsers 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. Service B directly passes the query parameters to Service A
Service A:
/** * Receive parameter passing* Receive the following three key values pairs* 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 { // Get the file path to 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("Output file error"); } }Service B:
/** * * @param busicode The business encoding exported can determine that a certain module does the export operation* @param values Request parameters* * Pass complex parameters through restTemplate* Return the file stream and let the browser pop up to download it. Currently, it is necessary to solve the problem of responding to the byte stream to the browser's console. The method of url downloading is used afterwards*/ @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("Parameter incorrect, please check whether the parameters are correct, busiCode ?"); } // Get the execution process Map map = excuteRestTemplate(busiCode,values); String path = (String)map.get("filepath"); byte[] excel = FastDFSClient.downloadToBytes(path); CmdExportConfigDto cmdExportConfig = exportService.getCmdExportConfigByBusiCode(busiCode); //Get the file name String fileName = cmdExportConfig.getReportName(); //Get the file suffix name 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); } /** * Execute request call* @param busiCode * @param variables * @return */ private Map exhaustRestTemplate(String busiCode,Map variables){ String serviceId=""; //Query export configuration CmdExportConfigDto cmdExportConfig = exportService.getCmdExportConfigByBusiCode(busiCode); serviceId = cmdExportConfig.getSystemType(); if(cmdExportConfig==null){ throw new BusinessRuntimeException("Unable to export without export configuration"); } //Get the export field information based on the export configuration id List<CmdExportFieldConfigDto> exportFieldList = exportService.getAllCmdExportFieldConfigDtoByConfigId(cmdExportConfig.getId()); if(StringUtils.isBlank(serviceId)){ throw new BusinessRuntimeException("Exported service not configured"); } 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); }Setting up the browser header
/** * Set the URL encoding of the download file according to different browser types* @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 browser finalFileName = URLEncoder.encode(fileName,"UTF-8"); }else if(StringUtils.contains(userAgent, "Mozilla")){//google, Firefox finalFileName = new String(fileName.getBytes("GBK"), "ISO8859-1"); }else{ finalFileName = URLEncoder.encode(fileName,"UTF-8");//Other browsers} return finalFileName; }Summarize
The above is the Spring cloud restTemplate method (multiple objects) introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!