Feign远程调用
一、Feign远程调用:
个人理解
服务A调用服务B, 服务A引入服务B的依赖,然后调用服务B FeignClient中的方法,该方法就会根据设置好的地址寻找FeignController中的对应接口,在该接口里面调用service,就可以实现一个Feign调用了
服务A
FeignResult feignResult = licenseCheckFeign.checkImportUser(orgId,source);
服务B
FeignClient
@FeignClient(value = "dqsf-share-datasync", url = "${dqsf.application.dqsf-share-datasync.url:http://127.0.0.1:10004}", contextId = "LicenseCheckFeign",configuration = FeignConfiguration.class, fallback = LicenseCheckHystrix.class) public interface LicenseCheckFeign { @PostMapping(value = "/license/check/checkImportUser",consumes = MULTIPART_FORM_DATA_VALUE) FeignResult<Boolean> checkImportUser(@RequestParam("orgId") String orgId, @RequestPart(name = "file") MultipartFile source); }
熔断实现
@Slf4j @Component public class LicenseCheckHystrix implements LicenseCheckFeign { //FeignResult @Override public FeignResult checkImportUser(String orgId,MultipartFile source) { log.error("LicenseCheckHystrix checkImportUser # orgId:{}",orgId); throw new RestException("feign请求验证增加人员后是否达到通讯录限制失败"); } }
FeignController
@PostMapping("/license/check/checkImportUser") public Boolean checkImportUser(@RequestParam("orgId") String orgId, @RequestPart("file") MultipartFile source) throws Exception { //超出限制返回1 try { userInfoService.checkImportUser(orgId,source); return true; } catch (Exception e) { throw e; } }
service
//导入人员限额校验 void checkImportUser(String orgId, MultipartFile source) throws Exception;
serviceImpl
@Override public void checkImportUser(String orgId, MultipartFile source) throws Exception{ //获取当前租户下的总人数 Integer userNum = Math.toIntExact(this.getUserCount(orgId)); //获取license限额数量 Integer userMaxNum = LicenseApi.getUserMax(); //老用户直接放行 if(null == userMaxNum) { log.info("老用户,没有license限额"); } int lineLength = 0; // 声明workbook对象 Workbook workbook = null; try { workbook = (Workbook) WorkbookFactory.create(source.getInputStream()); Sheet sheet = workbook.getSheetAt(0); lineLength = sheet.getPhysicalNumberOfRows(); } catch (IOException e) { log.info("read fileLength failed."); } finally { try { if (workbook != null) { // workbook不为null则close workbook.close(); } } catch (Exception e) { log.info("close workbook is failed."); } } if (lineLength - 2 + userNum > userMaxNum) { throw new RestException("抱歉,您的版本数据余额已用完,无法创建"); } }
二、MultipartFile file类型文件Feign远程接收出现"Current request is not a multipart request"问题
参照格式
@PostMapping(value = “/dsf/file/putFile”, consumes = MULTIPART_FORM_DATA_VALUE)
Map<String, Object> putFile(@RequestHeader(name = “X-Auth0-Token”) String token, @RequestPart(“file”) MultipartFile file, @RequestParam(value = “transfer”) Integer transfer);
注意
consumes = MULTIPART_FORM_DATA_VALUE
注意FeignControoller使用@RequestPart注解接收