마이크로 서비스를 사용할 때는 종종 서비스 간 전화를받는 데 어려움이 있습니다. Spring Cloud는 Feign 인터페이스 호출 및 RestTemplate 호출을 제공합니다.
여기서는 resttemplate 호출 방법에 대해 논의 할 것입니다.
서비스 A :이 세 매개 변수를 수신하는 세 가지 객체 매개 변수는 데이터베이스를 통해 쿼리됩니다.
서비스 B : 서비스를 호출하려면 서비스 B는 세 가지 매개 변수를 쿼리하는 메소드를 제공하며 나중에 3 개의 매개 변수를 사용해야합니다.
서비스 A의 경우이를 처리하는 두 가지 방법이 있습니다.
1. Service B는 세 가지 매개 변수를 쿼리하는 방법을 공개하기위한 Feign 인터페이스를 제공합니다. 서비스 a 직접 참조 쿼리 매개 변수에 feign을 참조하십시오. 서비스 B는 과거에 세 가지 쿼리 키워드를 전달하면됩니다.
행동을 서비스하십시오
@postmapping ( "/import/{busicode}/{filepath}")) public map <string, string> importexcel ( "Filepath") String FilePath,@pathVariable ( "Busicode") String Busicode,@requestible map <string, string> params, httpservletrequest) 응답 .SetchAracterEncoding ( "UTF-8"); userInfo user = userutil.getUser (); return ExcelService.importexcel (Filepath, Busicode, Params, User); } 서비스 서비스
// Feign 인터페이스 소개 개인 ExcelfReign ExcFelfReign을 소개합니다. 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 (excfLeign.class); cmdimportconfigdto configdto = xcelfreign.getcmdimportconfigbybusicode (busicode); cmdimportdto importdto = new Cmdimportdto (); importDto.setImportConfigid (configdto.getId ()); importdto.setexcelpath (Filepath); importdto.setparam (new GsonBuilder (). create (). tojson (params)); importDto.setLog ( ""); 긴 임시 = null; try {infid = long.valueof (xcelfreign.savecmdimportdto (importdto)); } catch (예외 e1) {e1.printstacktrace (); result.put ( "오류", "저장하는 동안 예외가 발생했습니다"); result.put ( "메시지", e1.getMessage ()); 반환 결과; } try {excelfreign.upDateImportStatus (infid, impind, importConstant.importStatus.Submit, "성공 제출"); } catch (예외 e) {e.printstacktrace (); } validateTask validateTask = new ValidateTask (); validateTask.init (infid, filepath, busicode, params, user); 문자열 메시지; try {message = validateTask.call (); } catch (예외 e) {e.printstacktrace (); result.put ( "오류", "예외는 확인에서 발생했습니다"); result.put ( "메시지", e.getMessage ()); 반환 결과; } if (message! = null) {result.put ( "error", "volification delting"); result.put ( "메시지", 메시지); 반환 결과; } persisttask peristtask = new PersistTask (); persisttask.init (infid, filepath, busicode, params, user); result.putall (importqueue.submit (peristtask)); 반환 결과; }서비스에 의해 제공되는 B-fegin b
@feignclient (value = "frame-service", path = "/excelapi/v1") public interface excelfreign excelapi {}서빙 B API 층 B-API
public interface ExcelApi {/** * 업데이트 상태 * @param infid * @param importType * @poram result */@postmapping ( "/updateImportStatus/{infIdInd}/{result}") void updateImportStatus (@PathVariable (@PathVariable ( "infId") long inmID, @Patpvarivel ( "") @PathVariable ( "result") String result)는 예외를 던집니다. /** * 가져 오기 구성 항목 * @param busicode * @return */@getMapping ( "/getImportConfig/{busicode}") cmdimportConfigdto getCmdimportConfigByBusicode (@PathVariable ( "busicode") 문자열 busicode); /** * 정보 저장 * @param importDto * @return */@postmapping ( "/saveImport") String SaveCmdImportDto (@RequestBody cmdimportdto importDto); }서비스 B는 API 인터페이스의 동작을 구현합니다
@RestController @RequestMapping ( "/ExcelApi/v1") 공개 클래스 ExcelFeignaction은 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/{infid}/{importtype}/{result}") public void updateimportStatus (@PathVariable ( "ImpID") long impid, @PathVariable ( "importType")) @PathVariable ( "result") string result) 예외 {cmdimportservice.updateimportstatus (infid, importStatus, new date (), result); }/** * 정보 저장 * @param importdto * @return */@postmapping ( "/saveimport") public String savecmdimportdto (@requestbody cmdimportdto importDto) {try {cmdimportService.saveCmdimportDto (importDto); return importDto.getId (); } catch (예외 e) {e.printstacktrace (); 새로운 BusinessRuntImeexception ( "시스템 예외")을 던지십시오. }}}서비스 B는 서비스를 액션 계층으로 부릅니다
/***** @param busicode 내보내는 비즈니스 인코딩은 모듈이 그것을 내보낼 수 있다고 결정할 수 있습니다* @param 값 요청 매개 변수** resttemplate를 통해 복잡한 매개 변수를 통과 할 수 있습니다* 파일 스트림을 반환하고 브라우저가 팝업을 다운로드하도록*/@postmapping (value = "/export/v3/{busicode}") expdownloadv3 (@pathvariable ( "busicode") 문자열 busicode, @requestbody map <string, object> value, httpservletrequest 요청) {if (stringUtils.isblank (busicode)) {새로운 BusinessRuntImeexception ( "매개 변수가 정확한지, 파라미터가 정확한지, 버드 시코 코드인지 확인하십시오."); } // 실행 프로세스 맵 맵 = resttemplate.postforObject ( "http : //" + serviceid + "/excelapi/v1/filename"/"+busicode,values ,map.class); String) map.get ("filepath "); byte [] byte [] excel = fastdfsclient.downtobys (partoby); cmdexportconfigdto cmdexportconfig = exportservice.getcmdexportconfigbusicode (busicode); HEADERS = 새로운 httpheaders (); frameurlconstants.transfromfilename (useragent, filename) + "<byte []>2. 서비스 B는 쿼리 매개 변수를 직접 전달하여
서비스 A :
/** * 매개 변수 수신 * 다음 세 가지 주요 값 수신 다음 세 가지 핵심 값 쌍 * cmdexportConfig : cmdexportConfigdto * ExportFieldList : list <cmdexportfieldconfigdto> * params : map * @param params * @param request * @param 응답 * @RepostMapping (@Report/v2 ")) map <string, object> params, httpservletrequest 요청, httpservletresponse 응답) {response.setcharacterencoding ( "utf-8"); {// 파일 경로를 ObjectMapper Mapper = 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 <CMDEXPORTFINTCONFIGDTO> () {}); } map 값 = (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); 새로운 응답 센터를 반환합니다 (Map, httpstatus.ok); } catch (ioexception e) {throw new runtimeexception ( "출력 파일 오류"); }}서비스 B :
/**** @param busicode 내보내는 비즈니스 인코딩으로 내보내는 비즈니스 인코딩은 특정 모듈이 내보내기 작업을 수행한다는 것을 결정할 수 있습니다.* @param 값 요청 매개 변수** RestTemplate를 통해 복잡한 매개 변수를 통과합니다.* 파일 스트림을 반환하고 브라우저가 팝업하여 다운로드하십시오. 현재 바이트 스트림에 브라우저 콘솔에 응답하는 문제를 해결해야합니다. URL 다운로드 방법은 나중에*/@postmapping (value = "/export/v3/{busicode}", produces = mediaType.text_plain_value) @ResponseBody public response entity <byte []> expdownloadv3 (@pathvariable ( "busicode") String, @객체 값, ht value, ht value, ht value, ht value, httperver 요청)은 예외를 {String busicode = values.get ( "busicode"). toString (); if (stringUtils.isblank (busicode)) {thring new businessRuntImeexception ( "매개 변수가 잘못된 경우 매개 변수가 올바른지 확인하십시오."); } // 실행 프로세스를 가져옵니다 맵 맵 = ExcuterestTemplate (Busicode, value); 문자열 path = (문자열) map.get ( "FilePath"); 바이트 [] excel = fastdfsclient.downloadtobytes (경로); cmdexportconfigdto cmdexportconfig = ExportService.getCmdexportConfigByBusicode (Busicode); // 파일 이름 문자열 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 ( "첨부 파일", frameUrlConstants.TransFromFilename (userAgent, filename) + "." + extFilename); 새로운 응답 entity를 반환 <byte []> (Excel, 헤더, httpstatus.ok); } / ** * 요청 호출 * @param busicode * @param 변수 * @return * / private map purrestestTemplate (String busicode, map 변수) {String serviceD = ""; // 쿼리 내보내기 구성 cmdexportconfigdto cmdexportConfig = ExportService.getCmdexportConfigByBusicode (busicode); serviceid = cmdexportconfig.getsystemtype (); if (cmdexportconfig == null) {새 BusinessRuntImeexception 던지기 ( "내보내기 구성없이 내보내기 할 수 없음"); } // 내보내기 구성 ID 목록을 기반으로 내보내기 필드 정보 가져 오기 <cmdexportfieldConfigdto> ExportFieldList = ExportService.getAllCMDEXPONTFINTCONFIGDTOBYCONFIGID (cmdexportConfig.getId ()); if (stringUtils.isblank (service)) {새로운 BusinessRuntImeexception ( "내보낸 서비스가 구성되지 않음"); } map <string, object> urivariables = new Hashmap <> (); urivariables.put ( "cmdexportconfig", cmdexportconfig); urivariables.put ( "ExportfieldList", ExportFieldList); urivariables.put ( "params", 변수); return resttemplate.postforoBject ( "http : //" + serviceid + "/ExcelService/Export/v2", New Httpentity (urivariable), map.class); }브라우저 헤더 설정
/ ** * 다른 브라우저 유형에 따라 다운로드 파일의 URL 인코딩을 설정합니다 * @param userAgent * @param filename * @Throws Exception */ public static String transfromFileName (String UserAgent, String Filename) 예외 {String finalFilename = ""; if (stringUtils.contains (userAgent, "msie")) {// 브라우저 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"); // 다른 브라우저} return finalfilename; }요약
위는 편집기가 소개 한 Spring Cloud RestTemplate 메소드 (다중 객체)입니다. 나는 그것이 당신에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!