FastDFS安装配置,与SpringBoot整合

FastDFS安装

安装 FastDFS 依赖

git clone https://hub.0z.gs/happyfish100/libfastcommon.git --depth 1
cd libfastcommon/
./make.sh && ./make.sh install

安装 FastDFS

git clone https://github.com/happyfish100/fastdfs.git --depth 1 
cd fastdfs/ 													
./make.sh && ./make.sh install 									
cp /root/fastdfs/conf/http.conf /etc/fdfs/
cp /root/fastdfs/conf/mime.types /etc/fdfs

下载 Nginx 的 FastDFS 模块

方便直接 http 访问 FastDFS 保存的文件

git clone https://hub.0z.gs/happyfish100/fastdfs-nginx-module.git --depth 1
cp /root/fastdfs-nginx-module/src/mod_fastdfs.conf /etc/fdfs

安装 Nginx

如果已经安装完了请忽略
nginx 只在 storager 服务器上安装

#安装 Nginx 依赖
yum -y install pcre-devel
yum install -y zlib-devel

#安装 Nginx
wget http://nginx.org/download/nginx-1.15.4.tar.gz
tar -zxvf nginx-1.15.4.tar.gz
cd nginx-1.15.4/
./configure --add-module=/root/fastdfs-nginx-module/src/
make && make install

至此,相关安装完成,下面是配置相关内容

配置 fastdfs 集群

# 配置hosts,此步可忽略
vim /etc/hosts

10.211.55.12 fastdfs12.com
10.211.55.13 fastdfs13.com

配置 tracker

#配置tracker
vim /etc/fdfs/tracker.conf
#需要修改的内容如下
port=22122 # tracker服务器端口(默认22122,一般不修改)
base_path=/root/data/fastdfs # 存储日志和数据的根目录

配置 storager

#配置 storager
vim /etc/fdfs/storage.conf
#需要修改的内容如下
port=23000 # storage服务端口(默认23000,一般不修改)
base_path=/data/fastdfs # 数据和日志文件存储根目录
store_path0=/data/fastdfs # 第一个存储目录
tracker_server=fastdfs.com:22122 # 服务器1
tracker_server=fastdfs2.com:22122 # 服务器2
tracker_server=fastdfs3.com:22122 # 服务器3
http.server_port=80 # http访问文件的端口(默认8888,看情况修改,和nginx中保持一致)

配置 nginx.conf

#配置 Nginx
#如果出现404或者无法访问的情况在 nginx.conf 文件头部加上 user root;
vim /usr/local/nginx/conf/nginx.conf
#添加如下配置
server {
	listen 80; ## 该端口为 storage.conf 中的 http.server_port 相同检测集群
	server_name localhost;
	location ~/group[0-9]/M00/ {
		ngx_fastdfs_module;
	} 
	error_page 500 502 503 504 /50x.html;
	location = /50x.html {
		root html;
	}
}

永久关闭防火墙

如果线上服务器开放相关端口

systemctl disable firewalld.service

启动服务

#启动 tracker
/usr/bin/fdfs_trackerd /etc/fdfs/tracker.conf
#启动 storage
/usr/bin/fdfs_storaged /etc/fdfs/storage.conf
# 重启 storage
/usr/bin/fdfs_storaged /etc/fdfs/storage.conf restart

检测集群

/usr/bin/fdfs_monitor /etc/fdfs/storage.conf

SpringBoot 整合 FastDFS

pom.xml

 <!-- fastdfs-->
        <dependency>
            <groupId>com.github.tobato</groupId>
            <artifactId>fastdfs-client</artifactId>
            <version>1.27.2</version>
        </dependency>

yml 配置文件

# 分布式文件系统fastdfs配置
fdfs:
  # socket连接超时时长
  soTimeout: 1500
  # 连接tracker服务器超时时长
  connectTimeout: 600
  pool:
    # 从池中借出的对象的最大数目
    max-total: 153
    # 获取连接时的最大等待毫秒数100
    max-wait-millis: 102
  # 缩略图生成参数,可选
  thumbImage:
    width: 150
    height: 150
  # 跟踪服务器tracker_server请求地址,支持多个,这里只有一个,如果有多个在下方加- x.x.x.x:port
  trackerList:
    - 10.211.55.12:22122
    - 10.211.55.13:22122
  web-server-url: http://10.211.55.16/

spring:
  servlet:
    multipart:
      max-file-size: 100MB
      max-request-size: 100MB

server:
  port: 8111
  servlet:
    context-path: /fdfs

FastDFS Client

package com.example.fdfs.config;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
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 java.io.*;

/**
 * @author Xiaolinag Ma
 * @date 2022年03月04日 14:54
 */
@Component
public class FastDFSClient {

    private static Logger log = LoggerFactory.getLogger(FastDFSClient.class);

    private static FastFileStorageClient fastFileStorageClient;

    private static FdfsWebServer fdfsWebServer;

    @Autowired
    public void setFastDFSClient(FastFileStorageClient fastFileStorageClient, FdfsWebServer fdfsWebServer) {
        FastDFSClient.fastFileStorageClient = fastFileStorageClient;
        FastDFSClient.fdfsWebServer = fdfsWebServer;
    }

    public static void main(String[] args) {
        String filePath = "/Users/maxiaoliang/Pictures/wallhaven-gjlg2q.png";
        File file = new File(filePath);
        FastDFSClient.uploadFile(file);
    }

    /**
     * @param multipartFile 文件对象
     * @return 返回文件地址
     * @author Xiaoliang Ma
     * @description 上传文件
     */
    public static String uploadFile(MultipartFile multipartFile) {
        try {
            StorePath storePath = fastFileStorageClient.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(), FilenameUtils.getExtension(multipartFile.getOriginalFilename()), null);
            return storePath.getFullPath();
        } catch (IOException e) {
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * @param multipartFile 图片对象
     * @return 返回图片地址
     * @author Xiaoliang Ma
     * @description 上传缩略图
     */
    public static String uploadImageAndCrtThumbImage(MultipartFile multipartFile) {
        try {
            StorePath storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(multipartFile.getInputStream(), multipartFile.getSize(), FilenameUtils.getExtension(multipartFile.getOriginalFilename()), null);
            return storePath.getFullPath();
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * @param file 文件对象
     * @return 返回文件地址
     * @author Xiaoliang Ma
     * @description 上传文件
     */
    public static String uploadFile(File file) {
        try {
            FileInputStream inputStream = new FileInputStream(file);
            StorePath storePath = fastFileStorageClient.uploadFile(inputStream, file.length(), FilenameUtils.getExtension(file.getName()), null);
            return storePath.getFullPath();
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * @param file 图片对象
     * @return 返回图片地址
     * @author Xiaoliang Ma
     * @description 上传缩略图
     */
    public static String uploadImageAndCrtThumbImage(File file) {
        try {
            FileInputStream inputStream = new FileInputStream(file);
            StorePath storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(inputStream, file.length(), FilenameUtils.getExtension(file.getName()), null);
            return storePath.getFullPath();
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * @param bytes byte数组
     * @param fileExtension 文件扩展名
     * @return 返回文件地址
     * @author Xiaoliang Ma
     * @description 将byte数组生成一个文件上传
     */
    public static String uploadFile(byte[] bytes, String fileExtension) {
        ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
        StorePath storePath = fastFileStorageClient.uploadFile(stream, bytes.length, fileExtension, null);
        return storePath.getFullPath();
    }

    /**
     * @param fileUrl 文件访问地址
     * @param file 文件保存路径
     * @author Xiaoliang Ma
     * @description 下载文件
     */
    public static boolean downloadFile(String fileUrl, File file) {
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            byte[] bytes = fastFileStorageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
            FileOutputStream stream = new FileOutputStream(file);
            stream.write(bytes);
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * @param fileUrl 文件访问地址
     * @author Xiaoliang Ma
     * @description 删除文件
     */
    public static boolean deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return false;
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            fastFileStorageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
        return true;
    }

    // 封装文件完整URL地址
    public static String getResAccessUrl(String path) {
        String url = fdfsWebServer.getWebServerUrl() + path;
        log.info("上传文件地址为:\n" + url);
        return url;
    }

}

测试

   @GetMapping("/upload")
    public void uploadTest() {
        String filePath = "/Users/maxiaoliang/Pictures/wallhaven-k98vem.jpg";
        File file = new File(filePath);
        String path = FastDFSClient.uploadFile(file);
        System.out.println(path);
        FastDFSClient.getResAccessUrl(path);

    }

保存成功返回连接

访问一下看看

虽然我不咋玩了,D.va我还是喜欢的

至此 FastDFS 的安装配置、与 SpringBoot 的整合到此结束


版权声明:本文为FuYaoPingBu原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。