基于tobato/FastDFS_Client支持SpringMvc改造

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wzl19870309/article/details/74049204

之前在项目中使用到了fastDFS,对于java客户端,最后决定采用tobato的fastDFS_Client。其源码在github上的链接

首先简单介绍下fastDFS_Client(以下摘自github)

在原作者YuQing与yuqih发布的java客户端基础上进行了大量重构工作,便于Java工作者学习与阅读

主要特性:
 1. 对关键部分代码加入了单元测试,便于理解与服务端的接口交易,提高接口质量 
 2. 将以前对byte硬解析风格重构为使用 对象+注解 的形式,尽量增强了代码的可读性 
 3. 支持对服务端的连接池管理(commons-pool2) 
 4. 支持上传图片时候检查图片格式,并且自动生成缩略图

之所以决定使用FastDFS_Client,主要原因是其支持连接池管理。但后来真正引入的时候,发现了问题。我们的项目没有使用到Spring-boot,而FastDFS_Client确需要Spring-boot做支持。没办法,最后决定最启动的一部分代码进行调整,以整合到我们的项目中去。下面就介绍一下,我所做的调整和思路:
1、采用Spring-boot无非是在系统启动的时候可以自动配置FastDFS_Client
2、使用SpringMVC的加载思路来替换掉Spring-boot

具体改动如下:
1、增加配置文件fastDFS.properties

#获取文件超时时间
fdfs.soTimeout = 30000
#连接超时时间
fdfs.connectTimeout = 20000
#图片压缩后宽度
fdfs.thumbImage.width = 150
#图片压缩收高度
fdfs.thumbImage.height = 150
#tracker配置,多个使用逗号隔开
fdfs.trackerLists=tracker_IP:22122
#前端获取url
fdfs.webServerUrl=https://……/

2、增加配置文件初识化

<!-- 引入属性配置文件 -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:config/fastDFS.properties</value>
            </list>
        </property>
    </bean>

3、修改PooledConnectionFactory.java

……
 /** 读取时间 */
@Value("${fdfs.soTimeout:30000}")
private int soTimeout;
   /** 连接超时时间 */
@Value("${fdfs.connectTimeout:10000}")
private int connectTimeout;
……

4、修改DefaultThumbImageConfig.java

@Value("${fdfs.thumbImage.width:150}")
private int width;

@Value("${fdfs.thumbImage.width:150}")
private int height;

5、修改FdfsWebServer.java

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

6、增加FastDFSClient.java

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.github.tobato.fastdfs.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;

@Component
public class FastDFSClient {

    private final Logger logger = LoggerFactory.getLogger(FastDFSClient.class);

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    /**
     * 上传文件
     * @param file 文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);
        return getResAccessUrl(storePath);
    }

    /**
     * 上传文件
     * @param file 文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    public String uploadFile(File file) throws IOException {
        FileInputStream inputStream = new FileInputStream (file);
        StorePath storePath = storageClient.uploadFile(inputStream,file.length(), FilenameUtils.getExtension(file.getName()),null);
        return getResAccessUrl(storePath);
    }

    /**
     * 将一段字符串生成一个文件上传
     * @param content 文件内容
     * @param fileExtension
     * @return
     */
    public 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 getResAccessUrl(storePath);
    }

    // 封装图片完整URL地址
    private String getResAccessUrl(StorePath storePath) {
        String fileUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
        return fileUrl;
    }

    /**
     * 删除文件
     * @param fileUrl 文件访问地址
     * @return
     */
    public void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            StorePath storePath = StorePath.praseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
            logger.warn(e.getMessage());
        }
    }

}

以上修改工作搞定,就可以在项目中直接注入FastDFSClient 进行使用了

猜你喜欢

转载自blog.csdn.net/wzl19870309/article/details/74049204