Spring cloud restTemplate 传递复杂参数的方式(多个对象)
程序员文章站
2023-12-18 17:31:10
使用微服务的时候往往服务之间调用比较麻烦,spring cloud提供了feign接口调用,resttemplate调用的方式
这里我探讨下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 { /** * 更新状态 * @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); } /** * 更新状态 * @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层
/** * * @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:
/** * 接收参数传递 * 分别接收下面三种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 导出的业务编码 能确定某个模块做导出操作 * @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); }
设置浏览器头
/** * 根据不同的浏览器类型设置下载文件的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 传递复杂参数的方式(多个对象),希望对大家有所帮助