1. 程式人生 > 遊戲 >戰地2042預載下載提速方法分享 最快104MB一秒

戰地2042預載下載提速方法分享 最快104MB一秒

Java操作FastDFS

1、建立 Springboot 工程

此處省略

2、引入 pom依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>net.oschina.zcx7878</groupId>
    <artifactId>fastdfs-client-java</artifactId>
    <version>1.27.0.0</version>
</dependency>

3、在 Resource 下建立 FastDFS配置檔案

fdfs_client.conf

connect_timeout = 60 # 連線超時時間,單位為秒
network_timeout = 60 # 通訊超時時間,單位為秒。傳送或接收資料時。假設在超時時間後還不能傳送或接收資料,則本次網路通訊失敗
charset = UTF-8 # 字符集
http.tracker_http_port = 8080 # .tracker的http埠
tracker_server = FastDFS的ip地址:22122 #  tracker伺服器IP和埠設定

4、在 Resource 下建立 application.yml

spring:
  servlet:
    multipart:
      max-request-size: 10MB
      max-file-size: 10MB
server:
  port: 9008

5、工具類

5.1 檔案實體類

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * description
 * author Admin
 * date 2021/11/27
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class FastDFSFile {

    /**
     * 檔名字
     */
    private String name;

    /**
     * 檔案內容
     */
    private byte[] content;

    /**
     * 副檔名
     */
    private String ext;

    /**
     * 檔案MD5摘要值
     */
    private String md5;

    /**
     * 檔案建立作者
     */
    private String author;

    public FastDFSFile(String name, byte[] content, String ext, String height, String width, String author) {
        super();
        this.name = name;
        this.content = content;
        this.ext = ext;
        this.author = author;
    }

    public FastDFSFile(String name, byte[] content, String ext) {
        super();
        this.name = name;
        this.content = content;
        this.ext =ext;
    }
}

5.2 檔案工具類,封裝底層方法

import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

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

/**
 * description FastDFS客戶端工具類
 * author Admin
 * date 2021/11/27
 */
public class FastDFSClient {
    private static Logger logger = LoggerFactory.getLogger(FastDFSFile.class);

    /**
     * 初始化載入 FastDFS的TrackerServer配置
     */
    static {
        try {
            String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
            ClientGlobal.init(filePath);
        } catch (Exception e) {
            logger.error("FastDFS 哭護短初始化失敗", e);
        }
    }

    /**
     * 檔案上傳
     * @param file
     * @return
     */
    public static String[] upload(FastDFSFile file) {
        // 獲取檔案的作者
        NameValuePair[] meta_list = new NameValuePair[1];
        meta_list[0] = new NameValuePair("author", file.getAuthor());

        // 接收返回資料
        String[] uploadResults = null;
        StorageClient storageClient = null;

        try {
            // 建立 StorageClient 客戶端物件
            storageClient = getTrackerClient();

            /**
             * 檔案上傳
             * 1) 檔案位元組陣列
             * 2) 副檔名
             * 3) 檔案作者
             */
            uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
        } catch (Exception e) {
            logger.error("上傳檔案失敗: " + file.getName(), e);
        }

        if (uploadResults ==null && storageClient != null) {
            logger.error("上傳檔案錯誤,錯誤碼: " + storageClient.getErrorCode());
        }
        // 獲取組名
        String groupName = uploadResults[0];
        // 獲取檔案儲存路徑
        String remoteFileName = uploadResults[1];
        return uploadResults;
    }

    /**
     * 獲取檔案資訊
     * @param groupName 組名
     * @param remoteFileName 檔案儲存完整名
     * @return
     */
    public static FileInfo getFile(String groupName, String remoteFileName) {
        try {
            StorageClient storageClient = getTrackerClient();
            return storageClient.get_file_info(groupName, remoteFileName);
        } catch (Exception e) {
            logger.error("從FastDFS中獲取檔案錯誤", e);
        }
        return null;
    }

    /**
     * 檔案下載
     * @param groupName
     * @param remoteFileName
     * @return
     */
    public static InputStream downFile(String groupName, String remoteFileName) {
        try {
            // 建立 StorageClient
            StorageClient storageClient = getTrackerClient();
            // 下載檔案
            byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
            ByteArrayInputStream ins = new ByteArrayInputStream(fileByte);
            return ins;
        } catch (Exception e) {
            logger.error("從FastDFS獲取檔案失敗", e);
        }
        return null;
    }

    /**
     * 檔案刪除
     * @param groupName
     * @param remoteFileName
     */
    public static  void deleteFile(String groupName, String remoteFileName) {
        try {
            // 建立 StorageClient
            StorageClient storageClient = getTrackerClient();
            // 刪除檔案
            int i = storageClient.delete_file(groupName, remoteFileName);
        } catch (Exception e) {
            logger.error("從FastDFS中檔案刪除失敗", e);
        }
    }

    /**
     * 獲取Storage組
     * @param groupName 組名
     * @return
     */
    public static StorageServer[] getStoreStorages(String groupName) {
        try {
            // 建立 TrackerClient
            TrackerClient trackerClient = new TrackerClient();
            // 獲取 TrackerServer
            TrackerServer trackerServer = trackerClient.getConnection();
            //獲取 Storage 組
            return trackerClient.getStoreStorages(trackerServer, groupName);
        } catch (Exception e) {
            logger.error("從FastDFS獲取Storage 組失敗", e);
        }
        return null;
    }

    /**
     * 獲取 Storage 資訊,IP和埠
     * @param groupName
     * @param remoteFileName
     * @return
     */
    public static ServerInfo[] getFetchStoages(String groupName, String remoteFileName) {
        try {
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
        } catch (Exception e) {
           logger.error("獲取Storage資訊,IP 和埠失敗", e);
        }
        return null;
    }

    /**
     * 獲取 Tracker 服務地址
     * @return
     */
    public static String getTrackerUrl() {
        return "http://" + getTrackerServer().getInetSocketAddress().getHostString()+":"+ClientGlobal.getG_tracker_http_port()+ "/";
    }

    /**
     * 獲取Storage 客戶端
     * @return
     */
    private static StorageClient getTrackerClient() {
        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = new StorageClient(trackerServer, null);
        return storageClient;
    }

    /**
     * 獲取 Tracker
     * @return
     */
    private static TrackerServer getTrackerServer() {
        try {
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            return trackerServer;
        } catch (Exception e) {
            logger.error("獲取Tracker 失敗", e);
        }
        return null;
    }
}

6、檔案上傳

@PostMapping("upload")
public Result upload(MultipartFile file) {
    try {
        // 檔案上傳
        // 1. 獲取檔案屬性
        // 1.1. 原始檔名
        String originalFilename = file.getOriginalFilename();
        // 1.2. 檔案內容
        byte[] fileBytes = file.getBytes();
        // 1.3 副檔名  test.jpg -> jpg
        String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

        // 2. 建立 FastDFSFile
        FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, fileBytes, ext);
        // 3. 呼叫工具類上傳
        // uploadResult 第一個只是 group 第二個值是:物理路徑
        String[] uploadResult = FastDFSClient.upload(fastDFSFile);

        // 預覽url
        String url = FastDFSClient.getTrackerUrl() + uploadResult[0] + "/" + uploadResult[1];

        return new Result(true, StatusCode.OK, "上傳成功",url);
    } catch (Exception e) {
        return new Result(false, StatusCode.ERROR, "上傳失敗" + e.getMessage());
    }
}