Feign使用
使用实例
//Feign
@FeignClient(name = "offline.client", url="EMPTY")
public interface OfflineClientFeign {
@GetMapping("")
String test(URI uri);
@PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
AsyncTaskInfo upload(URI uri,
@RequestHeader("Authorization") String token,
@RequestPart("file") MultipartFile file,
@RequestParam("param") String param);
}
//被Feign调用的接口
@PostMapping("/import")
public AsyncTaskInfo importFormData(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
ObjectMapper mapper = new ObjectMapper();
String paramJson = request.getParameter("param");
UploadParam param = null;
try {
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
param = mapper.readValue(paramJson, UploadParam.class);
} catch (IOException e) {
logger.error("出错原因:" + e.getMessage(), e);
}
return iUploadService.upload(file,param);
}
Feign动态IP调用
根据传入的URI进行接口调用,只需要在接口的第一个参数设置为URI
//URI对象创建示例
import java.net.URI;
new URI("http://www.baidu.com")
@FeignClient(name = "offline.client", url="EMPTY")
public interface OfflineClientFeign {
@GetMapping("")
String test(URI uri);
@PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
AsyncTaskInfo upload(URI uri,
@RequestHeader("Authorization") String token,
@RequestPart("file") MultipartFile file,
@RequestParam("param") String param);
}
Feign请求头携带token
@RequestHeader注解可以添加请求头
@FeignClient(name = "offline.client", url="EMPTY")
public interface OfflineClientFeign {
@GetMapping("")
String test(URI uri);
@PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
AsyncTaskInfo upload(URI uri,
@RequestHeader("Authorization") String token,
@RequestPart("file") MultipartFile file,
@RequestParam("param") String param);
}
Feign传递MultipartFile和对象
-
Feign传递MultipartFile
- 添加consumes = MediaType.MULTIPART_FORM_DATA_VALUE
- MultipartFile参数前添加@RequestPart(“file”)注解,其中"file"可以自定义,(@RequestParam可能也行,没有尝试)
-
同时传递对象
- 因为使用的HttpServletRequest获取部分请求参数,所以这里使用@RequestParam注解,并且param是Upload对象的JSON数据
-
MultipartFile对象创建,实现MultipartFile接口自定义实现,或者百度使用MockMultipartFile对象(自行百度)
public class DataUploadMultipartFile implements MultipartFile { private String name; private String originalFilename; private String contentType; private byte[] content; public DataUploadMultipartFile(String name, String originalFilename, String contentType, byte[] content) { this.name = name; this.originalFilename = originalFilename; this.contentType = contentType; this.content = content; } public DataUploadMultipartFile(String name, String originalFilename, String contentType, File file) throws IOException { this.name = name; this.originalFilename = originalFilename; this.contentType = contentType; this.content = IOUtils.toByteArray(new FileInputStream(file)); } @Override public String getName() { return name; } @Override public String getOriginalFilename() { return originalFilename; } @Override public String getContentType() { return contentType; } @Override public boolean isEmpty() { return content == null || content.length == 0; } @Override public long getSize() { return content.length; } @Override public byte[] getBytes() throws IOException { return content; } @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(content); } @Override public void transferTo(File dest) throws IOException, IllegalStateException { new FileOutputStream(dest).write(content); } public void setName(String name) { this.name = name; } public void setOriginalFilename(String originalFilename) { this.originalFilename = originalFilename; } public void setContentType(String contentType) { this.contentType = contentType; } public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } }
调用Feign接口示例
@Autowired注入offlineClientFeign,调用对应的Feign接口即可
@RestController
@RequestMapping("/data-upload")
public class DataUploadController {
@Autowired
private OfflineClientFeign offlineClientFeign;
@Autowired
private CacheObjectResourceRemote cacheObjectResourceRemote;
@PostMapping("/upload")
public AsyncTaskInfo upload(@RequestBody Map<String, Object> params) throws URISyntaxException, JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Object paramObj = params.get("param");
UploadParam param = mapper.convertValue(paramObj, UploadParam.class);
String uri = (String) params.get("uri");
String token = (String) params.get("token");
if (param == null || StringUtils.isEmpty(uri) || StringUtils.isEmpty(token)){
AsyncTaskInfo asyncTaskInfo = new AsyncTaskInfo();
asyncTaskInfo.setState(TaskState.ERROR);
asyncTaskInfo.setDetail("请求参数出错!");
}
//获取准备上传的文件
MultipartFile multipartFile = null;
if (StringUtils.isNotEmpty(param.getFileKey())){
multipartFile = getUploadFile(param.getFileKey());
if (multipartFile == null){
AsyncTaskInfo asyncTaskInfo = new AsyncTaskInfo();
asyncTaskInfo.setState(TaskState.ERROR);
asyncTaskInfo.setDetail("上传文件不存在!");
return asyncTaskInfo;
}
};
//将文件上传到网络端
AsyncTaskInfo asyncTaskInfo = offlineClientFeign.upload(new URI(uri),token, multipartFile, mapper.writeValueAsString(param));
return asyncTaskInfo;
}
//创建MultipartFile对象
private MultipartFile getUploadFile(String fileKey) {
//获取文件
String filePath = cacheObjectResourceRemote.find(fileKey);
File file = new File(FilenameUtils.normalize(filePath));
if (!file.exists() || !file.isFile() || file.length() <= 0) return null;
MultipartFile multipartFile = null;
//将File转换为MultipartFile
try {
multipartFile = new DataUploadMultipartFile(file.getName(),file.getName(),"MultipartFile",file);
} catch (IOException e) {
e.printStackTrace();
}
return multipartFile;
}
}