マイクロサービスを使用する場合、サービス間で電話をかけるのに苦労することがよくあります。 Spring Cloudは、Feign Interface CallsとRestTemplateコールを提供します。
ここでは、レストテンプレート呼び出しの方法について説明します。
サービスA:これらの3つのパラメーターを受信する3つのオブジェクトパラメーターは、データベースを介してクエリされています。
サービスB:サービスを呼び出すには、Service Bは3つのパラメーターを照会する方法を提供し、後で3つのパラメーターを使用する必要があります。
サービスAには、それに対処する2つの方法があります
1. Service Bは、3つのパラメーターを照会する方法を開示するためのPeignインターフェイスを提供します。サービスAは、クエリパラメーターに装いを直接参照します。 Service Bは、過去に3つのクエリキーワードを渡すだけです。
アクションにサービスを提供します
@postmapping( "/import/{busicode}/{filepath}")public map <string、string> importexcel(@pathvariable( "filepath")string filepath、@pathvariable( "busicode")string busicode、@requestbody map <string> string> params、httpservletreletreletresposs、 Response.setcharacterencoding( "utf-8"); userInfo user = userutil.getuser(); return excelservice.importexcel(filepath、busicode、params、user); }サービスサービス
// feign Interfaceを紹介しますプライベートエクセルフ補強補辞。パブリックマップ<文字列、文字列> 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(例外E1){e1.printstacktrace(); result.put( "error"、 "exceptionが保存中に発生した"); result.put( "message"、e1.getmessage());返品結果; } try {excelfReign.updateImportStatus(IMPID、importConstant.importStatus.submit、 "submit succunt"); } catch(Exception e){e.printstacktrace(); } validateTask validateTask = new validateTask(); validateTask.init(Impid、filepath、busicode、params、user);文字列メッセージ; try {message = validateTask.call(); } catch(Exception e){e.printstacktrace(); result.put( "error"、 "例外が検証で発生しました"); result.put( "message"、e.getmessage());返品結果; } if(message!= null){result.put( "error"、 "verification failed"); result.put( "message"、message);返品結果; } Perstask PersistTask = new PersistTask(); persisttask.init(Impid、filepath、busicode、params、user); result.putall(importqueue.submit(perstask));返品結果; }b-fegin Service b
@feignclient(value = "frame-service"、path = "/excelapi/v1")public interface excelfreignはexcelapi {}を拡張しますB APIレイヤーB-APIのサービング
public interface excelapi {/** * update status * @param impid * @param importtype * @param result */@postmapping( "/updateImportStatus/{Impid}/{ImportType}/{result}")void updateImportStatus( @pathvariable( "inpid")long ipd、 @poctoriaia " @pathvariable( "result")string result)例外をスローします。 /** *インポート構成項目を取得 * @param busicode * @return */@getMapping( "/getimportconfig/{busicode}")cmdimportconfigdto getcmdimportconfigbybusicode( @pathvariable( "busicode")string busicode); /** *情報を保存 * @param importdto * @return */@postmapping( "/saveimport")string savecmdimportdto(@requestbody cmdimportdto importdto); }サービスBは、APIインターフェイスのアクションを実装します
@RestController @RequestMapping( "/excelapi/v1")Public Class ExcelfignactionはExcelapi {@autowired private cmdexportservice exportserviceを実装しています。 /** *インポート構成項目を取得 * @param busicode * @return */@getMapping( "/getimportconfig/{busicode}")public cmdimportconfigdto getcmdimportconfigbybusicode( @pathvariable( "busicode")文字列busicode){return cmdimportconfigservice.getcmdimportconfigbybusicode(busicode); }/** *更新ステータス * @param Impid * @Param ImportStatus * @Param result */@PostMapping( "/updateImportStatus/{Impid}/{ImportType}/{result}")public void updateimportstatus( @pathvariable( "inpid")longimid、@pathvariable ") @pathvariable( "result")string result)スロー例外{cmdimportservice.updateimporttatus(inpid、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();新しいBusinessRuntimeException( "System Exception"); }}}サービスBは、サービスをアクションレイヤーに呼びます
/***** @param busicodeエクスポートされたビジネスエンコードは、モジュールがそれをエクスポートできると判断できます* @param値要求パラメーター** rettemplateを介して複雑なパラメーターを渡す*ファイルストリームを返し、 @postmapping(value = "/val/{busicode} @resposthodybody public expantive [] expdownloadv3( @pathvariable( "busicode")string busicode、@requestbody map <string、object> values、httpservletrequest request)スロー例外{if(stringutils.isblank(busicode)){throw new businessruntimeexcection( "パラメーターは正しいかどうかを確認してください。 } //実行プロセスの取得マップ= RESTTEMPLATE.POSTFOROBJECT( "http://" + serviceid + "/excelapi/v1/filename"/"+busicode,values,map.class); string path =(string)map.get( "filepath"); byte [] excel = fastdfsfsfsclient.down load.downodoby( "filepath"); cmdexportconfigdto cmdexportconfig = exportservice.getcmdexconfigbybusicodeヘッダー=新しいhttpheaders(); frameurlconstants.transfromfilename(useragent、filename) + extfilename <2。サービスBはクエリパラメーターを直接渡してサービスを提供します
サービスA:
/** *パラメーターの受信パス * Map <string、object> params、httpservletrequest request、httpservletresponse response){respons.setcharacterencoding( "utf-8"); try {// objectMapperへのファイルパスを取得= new objectMapper(); linkedhashmap requestparmap =(linkedhashmap)params.get( "cmdexportconfig"); cmdexportconfigdto cmdexportconfigdto = null;リスト<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);新しいResponseNtity(Map、httpstatus.ok)を返します。 } catch(ioException e){new nup runtimeexception( "出力ファイルエラー"); }}サービスB:
/**** @param busicodeエクスポートしたビジネスエンコードは、特定のモジュールがエクスポート操作を行うことを判断できます* @param値要求パラメーター**複雑なパラメーターをResttemplateに渡します*ファイルストリームを返し、ブラウザをポップアップしてダウンロードします。現在、ブラウザのコンソールにバイトストリームに応答する問題を解決する必要があります。 URLダウンロードの方法は、その後使用されます*/@PostMapping(value = "/export/v3/{busicode}"、生産= mediatype.text_plain_value)@responsebody public responsentity <byte []> expdownloadv3( @pathvariable( "busicode")String bustpret hap < request)スロー例外{string busicode = values.get( "busicode")。toString(); if(stringutils.isblank(busicode)){new businessRuntimeException( "パラメーターが正しくない、パラメーターが正しいかどうかを確認してください、busicode?"); } //実行プロセスマップを取得マップ= ExcuterestTemplate(busicode、values); string path =(string)map.get( "filepath"); byte [] excel = fastdfsclient.downloadtobytes(path); cmdexportconfigdto cmdexportconfig = exportservice.getcmdexportconfigbybusicode(busicode); //ファイル名を取得する文字列filename = cmdexportconfig.getReportName(); //ファイルの接尾辞名文字列extfileName = path.substring(path.lastindexof( '。')+1)を取得します。 httpheaders headers = new httpheaders(); eragent = request.getheader( "user-agent"); headers.setContentType(mediatype.application_octet_stream); headers.setContentDispositionFormData( "Attachment"、frameurrlconstants.transfromfilename(useragent、filename) + "。" + extfileName);新しいresponseNtity <byte []>(excel、headers、httpstatus.ok)を返します。 } / ** * request call * @param busicode * @param variables * @return * / private Map exhaustresttemplate(string busicode、map variables){string serviceid = ""; //クエリエクスポート構成cmdexportconfigdto cmdexportconfig = exportservice.getcmdexportconfigbybusicode(busicode); serviceId = cmdexportconfig.getSystemType(); if(cmdexportconfig == null){新しいbusinessRuntimeException( "エクスポートなしでエクスポートできない"); } //エクスポート構成IDリストに基づいてエクスポートフィールド情報を取得<CMDEXPORTFIELDCONFIGDTO> exportService.getAllcMDEXPORTFIELDCONFIGDTOBYCONFIGID(CMDEXPORTCONFIG.GETID(); if(stringutils.isblank(serviceId)){new businessRuntimeException( "Exported Service Not Configured"); } map <string、object> urivariables = new Hashmap <>(); urivariables.put( "cmdexportconfig"、cmdexportconfig); urivariables.put( "exportfieldlist"、exportfieldlist); urivariables.put( "params"、変数); RESTTEMPLATE.POSTFOROBJECT( "http://" + serviceId + "/excelservice/export/v2"、new httpentity(urivariables)、map.class); }ブラウザヘッダーのセットアップ
/ ** *さまざまなブラウザタイプに従ってダウンロードファイルのURLエンコードを設定 * @param useragent * @param filename * @return * @throws例外 */ public static string transfromfileName(string useragent、string filename)スロー例外{sring 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} finalFileNameを返します。 }要約します
上記は、編集者が紹介したSpring Cloud Restemplateメソッド(複数のオブジェクト)です。それがあなたに役立つことを願っています。ご質問がある場合は、メッセージを残してください。編集者は時間内に返信します。 wulin.comのウェブサイトへのご支援ありがとうございます!