Spring cloud restTemplate 传递复杂参数的方式(多个对象)
使用微服务的时候往往服务之间调用比较麻烦,springcloud提供了Feign接口调用,RestTemplate调用的方式
这里我探讨下RestTemplate调用的方式:
服务A:接收三个对象参数 这三个参数的是通过数据库查询出来的
服务B:要调用服务A服务B提供了查询三个参数的方法,后面要使用三个参数
对于服务A,处理的方式有两中
1.服务B提供一个Feign接口将查询三个参数的方法公开,服务A直接引用Feign来查询参数,服务B只需要将三个查询关键字传递过去即可
服务Aaction
@PostMapping("/import/{busiCode}/{filePath}")
publicMapimportExcel(@PathVariable("filePath")StringfilePath,@PathVariable("busiCode")StringbusiCode,@RequestBodyMapparams,
HttpServletRequestrequest,HttpServletResponseresponse){
response.setCharacterEncoding("UTF-8");
UserInfouser=UserUtil.getUser();
returnexcelService.importExcel(filePath,busiCode,params,user);
}
服务Aservice
//引入Feign接口 privateExcelFreignexcelFreign; publicMapimportExcel(StringfilePath,StringbusiCode,Map params,UserInfouser){ Map result=newHashMap (); excelFreign=SpringTool.getApplicationContext().getBean(ExcelFreign.class); CmdImportConfigDtoconfigDto=excelFreign.getCmdImportConfigByBusiCode(busiCode); CmdImportDtoimportDto=newCmdImportDto(); importDto.setImportConfigId(configDto.getId()); importDto.setExcelPath(filePath); importDto.setParam(newGsonBuilder().create().toJson(params)); importDto.setLog(""); LongimpId=null; try{ impId=Long.valueOf(excelFreign.saveCmdImportDto(importDto)); }catch(Exceptione1){ e1.printStackTrace(); result.put("error","保存出现异常"); result.put("message",e1.getMessage()); returnresult; } try{ excelFreign.updateImportStatus(impId,ImportConstant.ImportStatus.SUBMIT,"提交成功"); }catch(Exceptione){ e.printStackTrace(); } ValidateTaskvalidateTask=newValidateTask(); validateTask.init(impId,filePath,busiCode,params,user); Stringmessage; try{ message=validateTask.call(); }catch(Exceptione){ e.printStackTrace(); result.put("error","验证出现异常"); result.put("message",e.getMessage()); returnresult; } if(message!=null){ result.put("error","验证不通过"); result.put("message",message); returnresult; } PersistTaskpersistTask=newPersistTask(); persistTask.init(impId,filePath,busiCode,params,user); result.putAll(ImportQueue.submit(persistTask)); returnresult; }
服务B提供的B-Fegin
@FeignClient(value="frame-service",path="/excelApi/v1")
publicinterfaceExcelFreignextendsExcelApi{
}
服务Bapi层B-api
publicinterfaceExcelApi{
/**
*更新状态
*@paramimpId
*@paramimportType
*@paramresult
*/
@PostMapping("/updateImportStatus/{impId}/{importType}/{result}")
voidupdateImportStatus(@PathVariable("impId")LongimpId,@PathVariable("importType")StringimportType,@PathVariable("result")Stringresult)throwsException;
/**
*获取导入配置项
*@parambusiCode
*@return
*/
@GetMapping("/getImportConfig/{busicode}")
CmdImportConfigDtogetCmdImportConfigByBusiCode(@PathVariable("busicode")StringbusiCode);
/**
*保存信息
*@paramimportDto
*@return
*/
@PostMapping("/saveImport")
StringsaveCmdImportDto(@RequestBodyCmdImportDtoimportDto);
}
服务B实现api接口的action
@RestController
@RequestMapping("/excelApi/v1")
publicclassExcelFeignActionimplementsExcelApi{
@Autowired
privateCmdExportServiceexportService;
/**
*获取导入配置项
*@parambusiCode
*@return
*/
@GetMapping("/getImportConfig/{busicode}")
publicCmdImportConfigDtogetCmdImportConfigByBusiCode(@PathVariable("busicode")StringbusiCode){
returncmdImportConfigService.getCmdImportConfigByBusiCode(busiCode);
}
/**
*更新状态
*@paramimpId
*@paramimportStatus
*@paramresult
*/
@PostMapping("/updateImportStatus/{impId}/{importType}/{result}")
publicvoidupdateImportStatus(@PathVariable("impId")LongimpId,@PathVariable("importType")StringimportStatus,@PathVariable("result")Stringresult)throwsException{
cmdImportService.updateImportStatus(impId,importStatus,newDate(),result);
}
/**
*保存信息
*@paramimportDto
*@return
*/
@PostMapping("/saveImport")
publicStringsaveCmdImportDto(@RequestBodyCmdImportDtoimportDto){
try{
cmdImportService.saveCmdImportDto(importDto);
returnimportDto.getId();
}catch(Exceptione){
e.printStackTrace();
thrownewBusinessRuntimeException("系统出现异常");
}
}
}
服务B调用服务A action层
/**
*
*@parambusicode导出的业务编码能确定某个模块做导出操作
*@paramvalues请求参数
*
*通过restTemplate传递复杂参数
*@return
*返回文件流让浏览器弹出下载
*/
@PostMapping(value="/export/v3/{busicode}")
@ResponseBody
publicResponseEntityexpDownLoadV3(@PathVariable("busicode")Stringbusicode,@RequestBodyMapvalues,HttpServletRequestrequest)throwsException{
if(StringUtils.isBlank(busicode)){
thrownewBusinessRuntimeException("参数错误,请检查参数是否正确,busicode?");
}
//获取执行过程
Mapmap=restTemplate.postForObject("http://"+serviceId+"/excelApi/v1/文件名"/"+busicode,values,Map.class);
Stringpath=(String)map.get("filepath");
byte[]excel=FastDFSClient.downloadToBytes(path);
CmdExportConfigDtocmdExportConfig=exportService.getCmdExportConfigByBusiCode(busicode);
//获取文件名
StringfileName=cmdExportConfig.getReportName();
//获取文件后缀名
StringextFileName=path.substring(path.lastIndexOf('.')+1);
HttpHeadersheaders=newHttpHeaders();
//获取用户浏览器的种类对不同的浏览器进行编码处理
finalStringuserAgent=request.getHeader("USER-AGENT");
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment",FrameUrlConstants.transFromFileName(userAgent,fileName)+"."+extFileName);
returnnewResponseEntity(excel,headers,HttpStatus.OK);
}
2.服务B将查询出来的参数直接传递给服务A
服务A:
/** *接收参数传递 *分别接收下面三种keyvalue的键值对 *cmdExportConfig:CmdExportConfigDto *exportFieldList:List*params:Map *@paramparams *@paramrequest *@paramresponse *@return */ @PostMapping("/export/v2") publicResponseEntityexportExcel(@RequestBodyMap params,HttpServletRequestrequest,HttpServletResponseresponse){ response.setCharacterEncoding("UTF-8"); try{ //将文件的路径获取到 ObjectMappermapper=newObjectMapper(); LinkedHashMaprequestParMap=(LinkedHashMap)params.get("cmdExportConfig"); CmdExportConfigDtocmdExportConfigDto=null; List exportFieldList=null; if(requestParMap.size()>0){ cmdExportConfigDto=mapper.convertValue(requestParMap,CmdExportConfigDto.class); } ArrayListarrayList=(ArrayList)params.get("exportFieldList"); if(arrayList.size()>0){ exportFieldList=mapper.convertValue(arrayList,newTypeReference (){}); } Mapvalues=(Map)params.get("params"); StringfilePath=excelService.exportExcel(cmdExportConfigDto,exportFieldList,params,request.getServletContext().getRealPath("/")); Map map=newHashMap (); map.put("filepath",filePath); returnnewResponseEntity(map,HttpStatus.OK); }catch(IOExceptione){ thrownewRuntimeException("输出文件出错"); } }
服务B:
/**
*
*@parambusicode导出的业务编码能确定某个模块做导出操作
*@paramvalues请求参数
*
*通过restTemplate传递复杂参数
*@return
*返回文件流让浏览器弹出下载目前需要解决将字节流响应到浏览器的控制台了后面均采用url下载的方式
*/
@PostMapping(value="/export/v3/{busicode}",produces=MediaType.TEXT_PLAIN_VALUE)
@ResponseBody
publicResponseEntityexpDownLoadV3(@PathVariable("busicode")Stringbusicode,@RequestBodyMapvalues,HttpServletRequestrequest)throwsException{
StringbusiCode=values.get("busiCode").toString();
if(StringUtils.isBlank(busiCode)){
thrownewBusinessRuntimeException("参数错误,请检查参数是否正确,busiCode?");
}
//获取执行过程
Mapmap=excuteRestTemplate(busiCode,values);
Stringpath=(String)map.get("filepath");
byte[]excel=FastDFSClient.downloadToBytes(path);
CmdExportConfigDtocmdExportConfig=exportService.getCmdExportConfigByBusiCode(busiCode);
//获取文件名
StringfileName=cmdExportConfig.getReportName();
//获取文件后缀名
StringextFileName=path.substring(path.lastIndexOf('.')+1);
HttpHeadersheaders=newHttpHeaders();erAgent=request.getHeader("USER-AGENT");
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment",FrameUrlConstants.transFromFileName(userAgent,fileName)+"."+extFileName);
returnnewResponseEntity(excel,headers,HttpStatus.OK);
}
/**
*执行请求调用
*@parambusiCode
*@paramvariables
*@return
*/
privateMapexcuteRestTemplate(StringbusiCode,Mapvariables){
StringserviceId="";
//查询导出配置
CmdExportConfigDtocmdExportConfig=exportService.getCmdExportConfigByBusiCode(busiCode);
serviceId=cmdExportConfig.getSystemType();
if(cmdExportConfig==null){
thrownewBusinessRuntimeException("没有导出配置无法导出");
}
//根据导出配置id获取导出字段信息
ListexportFieldList=exportService.getAllCmdExportFieldConfigDtoByConfigId(cmdExportConfig.getId());
if(StringUtils.isBlank(serviceId)){
thrownewBusinessRuntimeException("未配置导出的服务");
}
MapuriVariables=newHashMap<>();
uriVariables.put("cmdExportConfig",cmdExportConfig);
uriVariables.put("exportFieldList",exportFieldList);
uriVariables.put("params",variables);
returnrestTemplate.postForObject("http://"+serviceId+"/excelService/export/v2",newHttpEntity(uriVariables),Map.class);
}
设置浏览器头
/**
*根据不同的浏览器类型设置下载文件的URL编码
*@paramuserAgent
*@paramfileName
*@return
*@throwsException
*/
publicstaticStringtransFromFileName(StringuserAgent,StringfileName)throwsException{
StringfinalFileName="";
if(StringUtils.contains(userAgent,"MSIE")){//IE浏览器
finalFileName=URLEncoder.encode(fileName,"UTF-8");
}elseif(StringUtils.contains(userAgent,"Mozilla")){//google,火狐浏览器
finalFileName=newString(fileName.getBytes("GBK"),"ISO8859-1");
}else{
finalFileName=URLEncoder.encode(fileName,"UTF-8");//其他浏览器
}
returnfinalFileName;
}
总结
以上所述是小编给大家介绍的SpringcloudrestTemplate传递复杂参数的方式(多个对象),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!