Saat menggunakan Microservices, Anda sering mengalami kesulitan menelepon antar layanan. Spring Cloud menyediakan panggilan antarmuka dan panggilan resttemplate.
Di sini saya akan membahas metode panggilan resttemplate:
Layanan A: Tiga parameter objek yang menerima tiga parameter ini diminta melalui database.
Layanan B: Untuk menghubungi Layanan A Layanan B menyediakan metode untuk menanyakan tiga parameter, dan tiga parameter harus digunakan nanti.
Untuk layanan A, ada dua cara untuk menghadapinya
1. Layanan B menyediakan antarmuka berpura -pura untuk mengungkapkan metode permintaan tiga parameter. Layanan Referensi langsung berpura -pura ke parameter kueri. Layanan B hanya perlu melewati tiga kata kunci kueri di masa lalu.
Layanan tindakan
@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, pengguna); } Layanan Layanan
// memperkenalkan antarmuka private excelfreign private excelfreign; peta publik <string, string> importexcel (string filePath, string busicode, peta <string, string> params, userInfo user) {peta <string, string> result = new HashMap <string, string> (); excelfReign = springTool.getApplicationContext (). getBean (excelfreign.class); CMDIMPORTCONFIGDTO configdto = excelfReign.getCmDimportConfigByBusicode (Busicode); Cmdimportdto importdto = cmdimportdto baru (); imporDTO.setImportConfigId (configDto.getId ()); importdto.setexcelpath (filepath); importdto.setparam (GsonBuilder baru (). Create (). TOJSON (params)); importdto.setlog (""); Long Impid = NULL; coba {impid = long.ValueOf (excelfreign.savecmdimportdto (importdto)); } catch (Exception e1) {e1.printstacktrace (); result.put ("error", "pengecualian terjadi saat menyimpan"); result.put ("pesan", e1.getMessage ()); hasil pengembalian; } coba {excelfreign.updateImportStatus (impid, importConsant.importstatus.submit, "kirim sukses"); } catch (Exception e) {E.PrintStackTrace (); } ValidateTask validateTask = new validateTask (); validateTask.init (impid, filepath, busicode, params, pengguna); Pesan string; coba {message = validateTask.call (); } catch (Exception e) {E.PrintStackTrace (); result.put ("kesalahan", "pengecualian terjadi dalam verifikasi"); result.put ("pesan", e.getMessage ()); hasil pengembalian; } if (pesan! = null) {result.put ("error", "verifikasi gagal"); result.put ("pesan", pesan); hasil pengembalian; } PersidTask persistask = new persistTask (); persisttask.init (impid, filepath, busicode, params, pengguna); hasil. hasil pengembalian; }B-fegin disediakan oleh layanan b
@FeignClient (value = "frame-service", path = "/excelapi/v1") Antarmuka publik Excelferign memperluas excelapi {}Melayani B API Layer B-API
Antarmuka Publik Excelapi {/** * Pembaruan Status * @param Impid * @param ImportType * @param hasil */@postmapping ("/updateImportStatus/{Impid}/{importType}/{hasil}") void updateMportStatus (@pathvariable ("Imprip") longyping, "Import") longaDePath, "IMPID") LongTypy, "Importpath," Importpatpath, "Importpatpat, @Pathvariable ("hasil") Hasil string) melempar pengecualian; /** * Dapatkan item konfigurasi impor * @param busicode * @return */@getmapping ("/getImportConfig/{Busicode}") cmDimportConfigdto getCMDImportConfigByBusicode (@pathvariable ("busicode") string busicode); /** * Simpan Informasi * @param Importdto * @return */@postmapping ("/saveImport") String saveCmDimportdto (@RequestBody cmdimportdto importdto); }Layanan B mengimplementasikan tindakan antarmuka API
@RestController @RequestMapping ("/excelapi/v1") Kelas publik Excelfeignaction mengimplementasikan Excelapi {@Autowired Private CMDExportService ExportService; /** * Dapatkan item konfigurasi impor * @param busicode * @return */@getmapping ("/getImportConfig/{busicode}") public cmdImportConfigdto getCmDimportConfigByBusicode (@pathvariable ("busicode") string busicode) {retrak 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") Hasil string) melempar Exception {cmDimportService.updateImportStatus (Impid, ImportStatus, new Date (), hasil); }/** * Simpan Informasi * @param Importdto * @return */@postmapping ("/saveImport") Public String savecmDimportdto (@RequestBody cmdimportdto importdto) {coba {cmDimportService.savecmdimportdto (importdto); pengembalian importdto.getId (); } catch (Exception e) {E.PrintStackTrace (); Lempar BusinessRunTimeException baru ("Pengecualian Sistem"); }}}Layanan B Memanggil Layanan Lapisan Tindakan
/***** @param Busicode Pode pengkodean bisnis yang diekspor dapat menentukan bahwa modul dapat mengekspornya* @param nilai -nilai permintaan parameter** lulus parameter kompleks melalui resplate* kembalikan aliran file dan biarkan browser muncul untuk mengunduh*/@postmapping (value = "/export/v3/{busicode} @postmapping (value ="/export/v3/{busicode} @postmapping (value = "/export/v3/{Busicode} @PosteBody @POSTE/VIEDEDE (BUSTEDE/V3/{BUSICODE") ExpDownLoadV3 (@PathVariable ("Busicode") String Busicode, @RequestBody Map <String, Object> Values, permintaan httpservletRequest) melempar pengecualian {if (stringutils.isblank (Busicode)) {throw BusinessRunTimeException ("Parameter tidak koreksi, BUSICODE Apakah Param } // Dapatkan peta proses eksekusi peta = restTemplate.postforObject ("http: //" + serviceId + "/excelapi/v1/filename"/"verbusicode, values,map.class); string path = (string) map.get (" filepath "); byte [] excel = excel = string = (string) map.get (" filepath "); byte [] excel = excel = everdown = foTDIENDOD. CMDExportConfigdo cmdExportConfig = ExportService.getCMDExportConfigbyBusicode (Busicode); headers = httpheaders baru (); FrameUrlConstants.transfromFileName (UserAgent, FileName) + "." + ExtfileName);2. Layanan B Langsung meneruskan parameter kueri ke layanan a
Layanan A:
/** * Menerima Parameter Passing * menerima tiga pasangan nilai utama berikut * CMDExportConfig: CMDExportConfigdto * ExportFieldlist: Daftar <CMDExportFieldConfigdto> * params: peta * @param params * @param response * @param * @return */@postmapping (" Peta <String, Object> Params, permintaan httpservletRequest, respons httpservletResponse) {response.setcharacterencoding ("UTF-8"); Coba {// Dapatkan jalur file ke ObjectMapper mapper = new ObjectMapper (); LinkedHashMap requestParmap = (linkedHashMap) params.get ("cmdexportConfig"); CmdExportConfigdto cmdExportConfigdto = null; Daftar <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, tipeer baru <cmdExportFieldConfigDto> () {}); } Peta values = (peta) params.get ("params"); String filePath = excelService.ExportExcel (cmdExportConfigdto, ExportFieldList, params, request.getServletContext (). GetRealPath ("/")); Peta <string, string> peta = new HashMap <String, String> (); Map.put ("FilePath", FilePath); return new responseentity (MAP, httpstatus.ok); } catch (ioException e) {throw runimeException baru ("kesalahan file output"); }}Layanan B:
/**** @param Busicode Pengkodean bisnis yang diekspor dapat menentukan bahwa modul tertentu melakukan operasi ekspor* @param nilai parameter permintaan** lulus parameter kompleks melalui restTemplate* Kembalikan aliran file dan biarkan browser muncul untuk mengunduhnya. Saat ini, perlu untuk menyelesaikan masalah menanggapi aliran byte ke konsol browser. 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 permintaan) melempar pengecualian {string busicode = values.get ("busicode"). ToString (); if (stringutils.isblank (busicode)) {lempar bisnis baruRuntiMeException ("Parameter salah, silakan periksa apakah parameternya benar, busicode?"); } // Dapatkan peta proses eksekusi peta = excuteresttemplate (busicode, nilai); String path = (string) map.get ("filepath"); byte [] excel = fastdfsclient.downloadtobytes (path); CmdExportConfigdto cmdExportConfig = ExportService.getCMDExportConfigByBusicode (Busicode); // Dapatkan nama file string filename = cmdexportConfig.getReportName (); // Dapatkan file suffix name string extfileName = path.substring (path.LastIndexof ('.')+1); Header httpheaders = httpheaders baru (); eragent = request.getHeader ("agen pengguna"); headers.setContentType (mediatype.application_octet_stream); headers.setContentDispositionFormData ("lampiran", frameurlconstants.transfromFileName (userAgent, fileName) + "." + extfileName); kembalikan responEntity baru <byte []> (excel, header, httpstatus.ok); } / ** * Jalankan panggilan permintaan * @param busicode * @param variabel * @return * / private Map exhaustrestTemplate (string busicode, variabel peta) {string serviceId = ""; // Konfigurasi Ekspor Kueri CMDExportConfigdto cmdExportConfig = ExportService.getCMDExportConfigByBusicode (Busicode); serviceId = cmdExportConfig.getSystemType (); if (cmdexportConfig == null) {lempar bisnis baruRuntiMeException ("Tidak dapat mengekspor tanpa konfigurasi ekspor"); } // Dapatkan informasi bidang ekspor berdasarkan daftar ID konfigurasi ekspor <cmdexportFieldConfigdto> ExportFieldList = ExportService.getAllCMDExportFieldConfigDTobyConfigId (cmdexportConfig.getID ()); if (stringutils.isblank (serviceId)) {lempar bisnis baruRunTimeException ("Layanan yang diekspor tidak dikonfigurasi"); } Peta <String, Object> Urivariables = HashMap baru <> (); Urivariables.put ("CMDExportConfig", CMDExportConfig); Urivariables.put ("ExportFieldList", ExportFieldList); Urivariable.put ("params", variabel); return resttemplate.postforObject ("http: //" + serviceId + "/excelservice/export/v2", httpentity baru (riivariable), peta.class); }Menyiapkan header browser
/ ** * Atur pengkodean URL dari file unduhan sesuai dengan tipe browser yang berbeda * @param userAgent * @param fileName * @return * @throws Exception */ public static string transfRomFileName (string userAgent, string file) lemparan pengecualian {string finalFileName = ""; if (stringutils.contains (userAgent, "msie")) {// IE browser finalFileName = urlencoder.encode (nama file, "utf-8"); } lain jika (stringutils.contains (userAgent, "mozilla")) {// google, firefox finalFileName = string baru (filename.getbytes ("gbk"), "iso8859-1"); } else {finalFileName = urlencoder.encode (nama file, "utf-8"); // browser lain} return finalFileName; }Meringkaskan
Di atas adalah metode Spring Cloud RestTemplate (beberapa objek) yang diperkenalkan kepada Anda oleh editor. Saya harap ini akan membantu Anda. Jika Anda memiliki pertanyaan, silakan tinggalkan saya pesan dan editor akan membalas Anda tepat waktu. Terima kasih banyak atas dukungan Anda ke situs web Wulin.com!