IILeeのBlog

IILeeのBlog

FastDFS 的 Java 客户端

878
2019-04-08
FastDFS 的 Java 客户端

前言

  • 前段时间搭建了一个FastDFS文件服务器想作为博客的图床,感觉服务器有点抗不太住,所以弃用了。但是既然搭都搭完了,不把个Java客户端弄出来总觉得自己的努力有点白费了。话不多说,上代码!

新建项目

新建SpringBoot工程,这里命名为:JavaFastDFSClient

编辑pom文件

在pom文件中引入如下jar包:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>
<!--引入FastDFS工具类-->
<dependency>
   <groupId>cn.bestwu</groupId>
   <artifactId>fastdfs-client-java</artifactId>
   <version>1.27</version>
</dependency>
<!--引入IO工具类库-->
<dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.6</version>
</dependency>

编辑配置文件

在resources目录下新建一个名为fdfs_client.conf的文件

connect_timeout = 60
network_timeout = 60
charset = UTF-8

# Tracker配置文件中配置的http端口
http.tracker_http_port = 9989
http.anti_steal_token = no
http.secret_key = FastDFS1234567890

# Tracker服务器地址
tracker_server = 你自己的IP:22122

如果按照博主之前的文章搭建的文件服务器,那么http.tracker_http_port的值应为9989,Tracker服务器地址的地址配置为自己的服务器IP端口,http.secret_key博主没有做配置,这里使用默认的就好。

FastDFS工具类

其中Slf4j可以去掉,博主为了方便直接进行了引入。

import lombok.extern.slf4j.Slf4j;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author chihiro
 * @date 2019/04/08
 */
@Slf4j
public class FastDFSClient {

    static {
        try {
            String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();

            ClientGlobal.init(filePath);
        } catch (Exception e) {
            log.error("FastDFS Client Init Fail!", e);
        }
    }

    /**
     * 文件上传
     *
     * @param file
     * @return 返回String[] [0]=groupName [1]=remoteFileName
     */
    public static String[] upload(FastDFSFile file) {
        log.info("File Name: " + file.getName() + "File Length:" + file.getContent().length);

        NameValuePair[] meta_list = new NameValuePair[1];
        meta_list[0] = new NameValuePair("author", file.getAuthor());

        long startTime = System.currentTimeMillis();
        String[] uploadResults = null;
        StorageClient storageClient = null;
        String path = null;
        try {
            storageClient = getTrackerClient();
            uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
            log.info("upload_file time used:" + (System.currentTimeMillis() - startTime) + " ms");
            if (uploadResults == null && storageClient != null) {
                log.error("upload file fail, error code:" + storageClient.getErrorCode());
            }
            String groupName = uploadResults[0];
            String remoteFileName = uploadResults[1];
            log.info("upload file successfully!!!" + "group_name:" + groupName + ", remoteFileName:" + " " + remoteFileName);
            return uploadResults;
        } catch (IOException e) {
            log.error("IO Exception when uploadind the file:" + file.getName(), e);
        } catch (Exception e) {
            log.error("Non IO Exception when uploadind the file:" + file.getName(), e);
        }
        return null;
    }

    public static FileInfo getFile(String groupName, String remoteFileName) {
        try {
            StorageClient storageClient = getTrackerClient();
            return storageClient.get_file_info(groupName, remoteFileName);
        } catch (IOException e) {
            log.error("IO Exception: Get File from Fast DFS failed", e);
        } catch (Exception e) {
            log.error("Non IO Exception: Get File from Fast DFS failed", e);
        }
        return null;
    }

    /**
     * 文件下载
     *
     * @param groupName
     * @param remoteFileName
     * @return
     */
    public static InputStream downFile(String groupName, String remoteFileName) {
        try {
            StorageClient storageClient = getTrackerClient();
            byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
            InputStream ins = new ByteArrayInputStream(fileByte);
            return ins;
        } catch (IOException e) {
            log.error("IO Exception: Get File from Fast DFS failed", e);
        } catch (Exception e) {
            log.error("Non IO Exception: Get File from Fast DFS failed", e);
        }
        return null;
    }

    /**
     * 删除文件
     *
     * @param groupName
     * @param remoteFileName
     * @return
     */
    public static void deleteFile(String groupName, String remoteFileName)
            throws Exception {
        StorageClient storageClient = getTrackerClient();
        int i = storageClient.delete_file(groupName, remoteFileName);
        log.info("delete file successfully!!!");
    }

    public static StorageServer[] getStoreStorages(String groupName)
            throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerClient.getStoreStorages(trackerServer, groupName);
    }

    public static ServerInfo[] getFetchStorages(String groupName,
                                                String remoteFileName) throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
    }

    public static String getTrackerUrl() throws IOException {
        return "http://" + getTrackerServer().getInetSocketAddress().getHostString() + ":" + ClientGlobal.getG_tracker_http_port() + "/";
    }

    private static StorageClient getTrackerClient() throws IOException {
        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = new StorageClient(trackerServer, null);
        return storageClient;
    }

    private static TrackerServer getTrackerServer() throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerServer;
    }

}

测试类

下面几个测试类实现了最基本的上传、下载以及删除功能。

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.csource.fastdfs.FileInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class FastDfsApplicationTests {

    @Test
    public void upload() throws IOException {
        File file = FileUtil.file("E:\\mnt\\file\\cms\\2019\\02\\22\\10.jpg");
        String fileName = FileUtil.getName(file);
        String extName = FileUtil.extName(fileName);
        System.out.println(fileName + extName);
        byte[] bytes = FileUtil.readBytes(file);
        FastDFSFile fastDFSFile = new FastDFSFile();
        fastDFSFile.setName(fileName);
        fastDFSFile.setExt(extName);
        fastDFSFile.setContent(bytes);
        fastDFSFile.setAuthor("333");
        String[] fileAbsolutePath = FastDFSClient.upload(fastDFSFile);
        if (!ArrayUtil.isNotEmpty(fileAbsolutePath)) {
            // 上传失败逻辑
            System.out.println("上传失败");
        } else {
            //TODO 正式环境切换
            String path = FastDFSClient.getTrackerUrl() + fileAbsolutePath[0] + "/" + fileAbsolutePath[1];
            log.info(path);
            log.info(JSON.toJSONString(fileAbsolutePath));
        }

    }

    @Test
    public void del() throws Exception {
        FastDFSClient.deleteFile("group1","M00/00/00/rBEcC1ykgdiALaceAACZsuwCbKE956.jpg");
    }

    @Test
    public void download() throws Exception {
        InputStream inputStream = FastDFSClient.downFile("group1", "M00/00/00/rBEcC1ykgdiALaceAACZsuwCbKE956.jpg");
        FileUtil.writeFromStream(inputStream,"E:\\mnt\\file\\6666.jpg");
    }

    @Test
    public void getFile() throws Exception {
        FileInfo fileInfo = FastDFSClient.getFile("group1", "M00/00/00/rBEcC1ykgdiALaceAACZsuwCbKE956.jpg");
        log.info(JSON.toJSONString(fileInfo));
    }

}

后记

  • 这套代码博主自己测试可以使用,但未经深度测试,只能算作一个参考demo。
  • 若遇到其他Bug,请联系博主。