Feign微服务调用文件上传微服务

引入openfeign

<springcloud.openfeign.version>2.1.1.RELEASE</springcloud.openfeign.version>

<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-openfeign</artifactId>
      <version>${springcloud.openfeign.version}</version>
</dependency>

文件上传微服务:

@RestController
@RequestMapping("/file")
public class UploadController {

    @Autowired
    private FastDfsService fastDfsService;

    /**
     * 单文件上传
     * @param file
     * @return
     */
    @PostMapping(value = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public JsonResult uploadFile(@RequestPart("file") MultipartFile file) {
        System.out.print("文件上传服务中:"+file.getOriginalFilename());
        Map<String, String> map = null;
        try {
            map = fastDfsService.uploadFile(file);
        } catch (IOException e) {
            new JsonResult<>(e);
        }
        return new JsonResult(map, "文件上传成功");
    }

    /**
     * 多文件上传
     * @param
     * @return
     */
    @PostMapping(value = "/uploadFiles",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public JsonResult uploadFiles(@RequestPart("files") MultipartFile[] files) {
        List<Object> data = new ArrayList<>();
        for (MultipartFile file:files){
            Map<String, String> map = null;
            try {
                map = fastDfsService.uploadFile(file);
                data.add(map);
            } catch (IOException e) {
                new JsonResult<>(e);
            }
        }
        return new JsonResult(data, "文件上传成功");
    }

    @PostMapping(value = "/deleteFile")
    public Map<String,Object> deleteFile(@RequestParam("fileUrl") String fileUrl){
        int t =  fastDfsService.deleteFile(fileUrl);
        Map<String,Object> message = new HashMap<>();
        if(t==1){
            message.put("code",1);
            message.put("msg","删除文件成功");
            return message;
        }
        message.put("code",0);
        message.put("msg","删除文件失败");
        return message;
    }


}

调用服务:

@FeignClient(value = "vcsrm-upload", configuration = UpLoadFeignClient.MultipartSupportConfig.class)
public interface UpLoadFeignClient {

    @PostMapping(value = "/file/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public JsonResult uploadFile(@RequestPart("file") MultipartFile file);

    @PostMapping(value = "/file/uploadFiles",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public JsonResult uploadFiles(@RequestPart("files") MultipartFile[] files);

    @PostMapping(value = "/file/deleteFile")
    public Map<String,Object> deleteFile(@RequestParam("fileUrl") String fileUrl);

    @Configuration
    class MultipartSupportConfig {

        @Bean
        public Encoder feignFormEncoder() {
            return new SpringFormEncoder();
        }
    }

}

UploadFileServiceImpl.java

@Service
public class UploadFileServiceImpl implements UploadFileService {

    @Autowired
    private  UpLoadFeignClient upLoadFeignClient;

    @Override
    public JsonResult uploadFile(MultipartFile file) {
        return upLoadFeignClient.uploadFile(file);
    }

    @Override
    public JsonResult uploadFiles(MultipartFile[] files) {
        return upLoadFeignClient.uploadFiles(files);
    }

    @Override
    public Map<String, Object> deleteFile(String fileUrl) {
        return upLoadFeignClient.deleteFile(fileUrl);
    }

}

 

配置fdfs文件服务器:

<fastDFS.client.version>1.26.1-RELEASE</fastDFS.client.version>

<!--FastDFS客户端-->
<dependency>
     <groupId>com.github.tobato</groupId>
     <artifactId>fastdfs-client</artifactId>
     <version>${fastDFS.client.version}</version>
</dependency>

application.yml或application.properties

 
server:
  port: 8082
spring:
  application:
    name: file-upload
  servlet:
    multipart:
      max-file-size: 10MB #限制文件大小

eureka:
  client:
    service-url:
      defaultZone: http://xx:xx@127.0.0.1:10086/eureka
  instance:
    ip-address: 127.0.0.1
    prefer-ip-address: true

fdfs:
  soTimeout: 1500 #socket连接超时时长
  connectTimeout: 600 #连接tracker服务器超时时长
  resHost: 61.157.96.xx
  storagePort: 22100
  thumbImage: #缩略图生成参数,可选
    width: 150
    height: 150
  trackerList: #TrackerList参数,支持多个,我这里只有一个,如果有多个在下方加- x.x.x.x:port
    - 61.157.96.82:22122

FastDFSConfig.java

@Component
@Data
public class FastDFSConfig {

    @Value("${fdfs.resHost}")
    private String resHost;

    @Value("${fdfs.storagePort}")
    private String storagePort;

}

FastDFSClientImporter.java

@Configuration
@Import(FdfsClientConfig.class)
 解决jmx重复注册bean的问题
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FastDFSClientImporter {

    @Bean
    public MultipartConfigElement multipartConfigElement(){
        MultipartConfigFactory factory = new MultipartConfigFactory();

        // 一个文件最大KB,MB
        factory.setMaxFileSize(DataSize.ofMegabytes(10));
        // 设置总上传数据总大小
        factory.setMaxRequestSize(DataSize.ofMegabytes(20));

        // 设置文件大小限制 ,超出设置页面会抛出异常信息,
        // 这样在文件上传的地方就需要进行异常信息的处理了;
        //factory.setMaxFileSize("128MB"); // KB,MB
        /// 设置总上传数据总大小
        //factory.setMaxRequestSize("256MB");
        //设置文件路径
        //factory.setLocation("/excel_src");

        return factory.createMultipartConfig();

    }
}

FastDfsService.java

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.domain.ThumbImageConfig;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.proto.storage.DownloadFileWriter;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.xx.upload.config.FastDFSConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * @data ${DATA}
 */
@Slf4j
@Component
public class FastDfsService {

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FastDFSConfig fastDFSConfig;   // 项目参数配置

    @Autowired
    private ThumbImageConfig thumbImageConfig;

    /**
     * 上传一个文件
     */
    public Map<String, String> uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return getResult(storePath);
    }

    /**
     * 将一段字符串生成一个文件上传
     */
    public Map<String, String> uploadFile(String content, String fileExtension) {
        byte[] buff = content.getBytes(Charset.forName("UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath storePath = storageClient.uploadFile(stream, buff.length, fileExtension, null);
        return getResult(storePath);
    }

    /**
     * 上传一张图片, 服务器生成2张图片, 一张原图, 一张缩略图
     */
    public Map<String, String> uploadImg(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadImageAndCrtThumbImage(
                file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
        String smallImgPath = thumbImageConfig.getThumbImagePath(storePath.getPath());
        Map<String, String> resultMap = getResult(storePath);
        resultMap.put("smallImgPath", smallImgPath);
        return resultMap;
    }

    // 封装上传的 返回结果
    private Map<String, String> getResult(StorePath storePath) {
        Map<String, String> resultMap = new HashMap<String, String>();
        String fileUrl = "http://" + fastDFSConfig.getResHost() + ":" + fastDFSConfig.getStoragePort() + "/" + storePath.getFullPath();
        resultMap.put("fileUrl", fileUrl);
        resultMap.put("fullPath", storePath.getFullPath());
        resultMap.put("path", storePath.getPath());
        resultMap.put("group", storePath.getGroup());
        return resultMap;
    }

    /**
     * 下载文件
     */
    public String downloadFile(String group, String path, String filePath) {
        String downloadFile = storageClient.downloadFile(group, path, new DownloadFileWriter(filePath));
        return downloadFile;
    }

    /**
     * 下载文件
     */
    public byte[] downloadFile(String group, String path) {
        byte[] bytes = storageClient.downloadFile(group, path, new DownloadByteArray());
        return bytes;
    }


    /**
     * 删除文件
     */
    public int deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return 0;
        }
        try {
            StorePath storePath = StorePath.praseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
            log.warn(e.getMessage());
            return 0;
        }
        return 1;
    }

    /**
     * 删除文件
     */
    public int deleteFile(String group, String path) {
        if (StringUtils.isEmpty(group) || StringUtils.isEmpty(path)) {
            return 0;
        }
        try {
            storageClient.deleteFile(group, path);
        } catch (Exception e) {
            log.warn(e.getMessage());
            return 0;
        }
        return 1;
    }
}

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
出现异常"could not extract response: no suitable httpclient found for response type"通常是由于open-feign微服务调用时,没有找到合适的http客户端来处理返回的响应类型引起的。 在使用open-feign进行微服务调用时,我们需要根据实际情况选择适合的http客户端来处理响应。通常open-feign会自动进行http客户端的选择和配置,但有些情况下可能会出现上述异常。 解决该异常的方法有以下几种: 1. 确保引入了适当版本的open-feign和相关依赖库。要使用open-feign,应该在pom.xml文件中添加相应的依赖,并确保其版本与当前使用的spring boot版本兼容。 2. 检查http客户端的配置。可以通过修改application.properties或application.yml文件设置http客户端的配置。例如,在application.properties文件中添加以下配置: ``` feign.httpclient.enabled=true feign.okhttp.enabled=false ``` 这将启用Apache HttpClient并禁用OkHttp客户端。 3. 如果仍然出现异常,可以尝试清除本地maven仓库并重新构建项目。有时候这种异常是由于maven仓库中缓存的库与实际所需版本不一致引起的。 总的来说,解决open-feign微服务调用异常"could not extract response: no suitable httpclient found for response type"的方法是确保使用了适当的open-feign版本,并根据需要调整http客户端的配置。如果仍然出现异常,可以尝试清除maven仓库并重新构建项目。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值