1. 程式人生 > 其它 >SpringBoot2.x整合FastDFS

SpringBoot2.x整合FastDFS

本篇部落格學習SpringBoot 2.1.11.RELEASE整合FastDFS。

FastDFS作用

FastDFS是一個開源的輕量級分散式檔案系統,它對檔案進行管理,功能包括:檔案儲存、檔案同步、檔案上傳、檔案下載等,解決了大容量儲存和負載均衡的問題。

安裝連線:

CentOS 7 安裝FastDFS V6.0.3

我們開始吧

新建一個springboot專案

pom檔案

加入fastdfs-client-java包

<dependency>
	<groupId>org.csource</groupId>
    <artifactId>fastdfs-client-java</artifactId>
    <version>1.27-SNAPSHOT</version>
</dependency>

注意:fastdfs-client-java包mvn庫中沒有編譯包,需要自己下載編譯到自己的mvn本地庫中,官方地址:https://github.com/happyfish100/fastdfs-client-java

fdfs_client.conf

resources資料夾下新建fdfs_client.conf,編寫如下:

connect_timeout = 2
network_timeout = 30
charset = UTF-8
http.tracker_http_port = 6666
http.anti_steal_token = no
http.secret_key = FastDFS1234567890
tracker_server = 192.168.31.100:22122

檔案工具類

編寫fastdfs初始化連線配置工具類

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.stereotype.Service;

import java.io.*;

@Service
public class FastDFSService {

    FastDFSService() throws IOException, MyException {
        ClientGlobal.init("fdfs_client.conf");
    }



    public String upload(byte[] bs, String stringbe) {
        TrackerServer trackerServer = null;
        StorageServer storageServer = null;
        String fileIds = null;
        try {
            trackerServer = init();
            StorageClient1 storageClient = new StorageClient1(trackerServer, storageServer);
            fileIds = storageClient.upload_file1(bs, getFileExt(stringbe), null);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        } finally {
            close(storageServer, trackerServer);
        }
        return fileIds;
    }

    public byte[] download(String groupName) {
        TrackerServer trackerServer = null;
        StorageServer storageServer = null;
        byte[] b = null;
        try {
            trackerServer = init();
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
            b = storageClient1.download_file1(groupName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(storageServer, trackerServer);
        }
        return b;
    }

    public FileInfo getFileInfo(String groupName) {
        TrackerServer trackerServer = null;
        StorageServer storageServer = null;
        FileInfo fi = null;
        try {
            trackerServer = init();
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
            fi = storageClient1.get_file_info1(groupName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(storageServer, trackerServer);
        }
        return fi;
    }

    public NameValuePair[] getFileMate(String groupName) {
        TrackerServer trackerServer = null;
        StorageServer storageServer = null;
        NameValuePair nvps[] = null;
        try {
            trackerServer = init();
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
            nvps = storageClient1.get_metadata1(groupName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(storageServer, trackerServer);
        }
        return nvps;
    }

    public int delete(String groupName) {
        TrackerServer trackerServer = null;
        StorageServer storageServer = null;
        int i = 0;
        try {
            trackerServer = init();
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
            i = storageClient1.delete_file1(groupName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(storageServer, trackerServer);
        }
        return i;
    }

    public byte[] File2byte(File file) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    private TrackerServer init() {
        TrackerServer trackerServer = null;
        try {
            TrackerClient tracker = new TrackerClient();
            trackerServer = tracker.getConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return trackerServer;
    }

    private void close(StorageServer storageServer, TrackerServer trackerServer) {
        try {
            if (storageServer != null) {
                storageServer.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (trackerServer != null) {
                trackerServer.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getFileExt(String fileName) {
        if (StringUtils.isBlank(fileName) || !fileName.contains(".")) {
            return "";
        } else {
            return fileName.substring(fileName.lastIndexOf(".") + 1); // 不帶最後的點

        }
    }

    public String getFileName(String fileName) {
        if (StringUtils.isBlank(fileName) || !fileName.contains("/")) {
            return "";
        } else {
            return fileName.substring(fileName.lastIndexOf("/") + 1); // 不帶最後的點

        }
    }
}

演示案例

編寫測試類

import cn.cicoding.service.FastDFSService;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootFastdfsApplicationTests {

    @Autowired
    private FastDFSService fastDFSService;

    @Test
    public void contextLoads() throws IOException {
        String local_filename = "C:\\Users\\Public\\Pictures\\Sample Pictures\\123.jpg";
        File f=new File(local_filename);
        String groupName= fastDFSService.upload(fastDFSService.File2byte(f),f.getName());
        System.out.println(groupName);
        IOUtils.write(fastDFSService.download(groupName), new FileOutputStream("D:/app/fastdfs/"+fastDFSService.getFileName(groupName)));
        System.out.println(fastDFSService.getFileInfo(groupName));
        System.out.println(fastDFSService.getFileMate(groupName));
        System.out.println(fastDFSService.delete(groupName)==0 ? "刪除成功" : "刪除失敗");

    }

}

執行測試類得到結果:

group1/M00/00/00/wKgfZF3vl6WAJDW5AAvWFlS1kOw230.jpg
123
.jpg
刪除成功

原始碼可以首頁加群獲取!