一、为什么要有转发
首先要了解跨域问题,此处不进行展开,总之 fate 框架不方便改且前端直接访问会产生跨域问题,所以写了一个中间件进行转发,服务之间的访问不会产生跨域,此外前端是部署在这个spring boot转发服务上的也不会产生跨域。
二、拿到一个 fate 的接口如何编写转发函数
通常是在这个文件中添加新接口
1.附带文件时,application-context为multipart,前端通过new FormData()来作为data
@RequestMapping(value = "/predict/batch", method = RequestMethod.POST)@ResponseBodypublic ResponseResult getPredictBatch(@RequestPart(value = "service_id") String service_id,@RequestPart(value = "file") MultipartFile file,@RequestPart(value = "name") String name,@RequestPart(value = "context") String context,BindingResult bindingResult) {if (bindingResult.hasErrors()) {FieldError errors = bindingResult.getFieldError();return new ResponseResult<>(ErrorCode.ERROR_PARAMETER, errors.getDefaultMessage());}MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();map.add("file", new FileSystemResource(convert(file)));map.add("service_id", service_id);map.add("context", context);map.add("name", name);HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.MULTIPART_FORM_DATA);HttpEntity<MultiValueMap<String, Object>> request =new HttpEntity<MultiValueMap<String, Object>>(map, headers);Map map1;try {map1 = restTemplate.postForObject(fateUrl + Dict.URL_PREDICT_BATCH, request, Map.class);} catch (Exception e) {logger.error("connect fateflow error:", e);return new ResponseResult<>(ErrorCode.FATEFLOW_ERROR_CONNECTION, null);}if (!map1.get("retcode").equals(0)) {return new ResponseResult(ErrorCode.SERVLET_ERROR, map1);}return new ResponseResult<>(ErrorCode.SUCCESS, map1);}
类似于此接口,只需要把所有请求到的参数写到函数的参数中去
封装请求的参数和Header(文件需要通过convert函数转成File格式)
然后通过 RestTemplate(SpringBoot封装的网络请求工具)进行转发
2.不附带文件,直接把参数放在axios请求的的data中
@RequestMapping(value = "/preprocess/data/cluster_data", method = RequestMethod.POST)@ResponseBodypublic ResponseResult postPreprocessClusterData(@RequestBody DataGetDTO dataGetDTO) {String result;try {result =httpClientPool.post(fateUrl + Dict.PREPROCESS_CLUSTER_DATA, JSON.toJSONString(dataGetDTO));} catch (Exception e) {logger.error("connect fateflow error:", e);return new ResponseResult<>(ErrorCode.FATEFLOW_ERROR_CONNECTION);}return ResponseUtil.buildResponse(result, null);}
代码格式固定,只需要自定义一个DTO文件作为参数即可,需要加get和set、构造函数等方法
public class DataGetDTO implements Serializable {private String file_path;private String[] feature;private String y_feat;private String y_feature;private String[] x_feat;private int n;....}
这里如果参数是一个对象(前端概念中的对象,这里指json格式),类型设置为 JSONObject
3.转发的路径和请求的路径需要保持一致,要在DICT文件中配置
三、关于访问路径
在application.yml中进行配置
正式上线后需要打开第三个注解(严格来说需要写三个配置文件,然后配置参数决定使用哪个配置文件,此处是为了方便开发)
