FastDFS安装、使用以及权限


学习来源

Centos7 上安装 FastDFS https://www.cnblogs.com/yufeng218/p/8111961.html
FastDFS服务器搭建 https://blog.csdn.net/prcyang/article/details/89946190

手把手教你用 FastDFS 构建分布式文件管理系统 https://blog.csdn.net/u012702547/article/details/104589468

FastDFS遇到的问题 https://blog.csdn.net/zhaoqi_i/article/details/100139968

Linux非root用户安装及配置Nginx[吊打某度95%以上的教程] https://cloud.tencent.com/developer/article/1555828

1、基础介绍

1.1 简介

FastDFS 专为互联网应用量身定做,解决大容量文件存储问题,追求高性能和高扩展性,它可以看做是基于文件的 key/value 存储系统,key 为文件 ID,value 为文件内容,因此称作分布式文件存储服务更为合适。

1.2 功能

作为一款分布式文件管理系统,FastDFS 主要包括四个方面的功能:

  • 文件存储
  • 文件同步
  • 文件上传
  • 文件下载

1.3 架构

FastDFS架构包括 Tracker server和Storage server。客户端请求Tracker server进行文件上传、下载,通过Trackerserver调度最终由Storage server完成文件上传和下载。

FastDFS 系统有三个角色:跟踪服务器(Tracker Server)、存储服务器(Storage Server)和客户端(Client)。

  Tracker Server:跟踪服务器,主要做调度工作,起到均衡的作用;负责管理所有的 storage server和 group,每个 storage 在启动后会连接 Tracker,告知自己所属 group 等信息,并保持周期性心跳。通过Trackerserver在文件上传时可以根据一些策略找到Storageserver提供文件上传服务。

  Storage Server:存储服务器,主要提供容量和备份服务;以 group 为单位,每个 group 内可以有多台 storage server,数据互为备份。Storage server没有实现自己的文件系统而是利用操作系统 的文件系统来管理文件。

  Client:客户端,上传下载数据的服务器,也就是我们自己的项目所部署在的服务器。

image-20210503232129139

2、安装和配置

2.1 环境准备

主要安装如下:

2.1 运行环境安装

2.1.1 安装编译依赖gcc环境

安装FastDFS需要先将官网下载的源码进行编译,编译依赖gcc环境

[root@localhost ~]# yum -y install gcc-c++

ps:检查gcc-c++是否已经安装(如果已安装,执行 yum -y install gcc-c++ 也会提示)

[root@localhost src]# whereis gcc   
gcc:[root@localhost src]#        # 未安装输出
gcc: /usr/bin/gcc /usr/lib/gcc /usr/libexec/gcc /usr/share/man/man1/gcc.1.gz        #已安装输出

2.1.2 安装libevent

FastDFS依赖libevent库,需要安装:

[root@localhost ~]# yum -y install libevent

2.1.3 安装libfastcommon

libfastcommon是FastDFS官方提供的,libfastcommon包含了FastDFS运行所需要的一些基础库。

[root@localhost ~]# cd /usr/local/src/    #切换到下载目录
[root@localhost src]# wget -O libfastcommon-1.0.39.tar.gz  https://codeload.github.com/happyfish100/libfastcommon/tar.gz/V1.0.39 #下载(如果下载慢 可以将下载好的文件上传到此目录)
[root@localhost src]# tar -zxvf libfastcommon-1.0.39.tar.gz      #解压
[root@localhost src]# cd libfastcommon-1.0.39/
# 安装
[root@localhost libfastcommon-1.0.39]# ./make.sh 

[root@localhost libfastcommon-1.0.39]# ./make.sh  install

2.2 FastDFS安装和配置

2.2.1 安装

接下来我们下载 Tracker,注意,由于 Tracker 和 Storage 是相同的安装包,所以下载一次即可

[root@localhost libfastcommon-1.0.39]# cd /usr/local/src/      #切换到下载目录
#下载(如果下载慢 可以将下载好的文件上传到此目录)
[root@localhost src]# wget -O fastdfs-5.11.tar.gz https://codeload.github.com/happyfish100/fastdfs/tar.gz/V5.11
[root@localhost src]# tar -zxvf fastdfs-5.11.tar.gz   #解压
[root@localhost src]# cd fastdfs-5.11/
#安装
[root@localhost fastdfs-5.11]# ./make.sh 
[root@localhost fastdfs-5.11]# ./make.sh  install

安装成功后,执行如下命令,将安装目录内 conf 目录下的配置文件拷贝到 /etc/fdfs 目录下:

cd conf/
cp ./* /etc/fdfs/

2.2.2 配置FastDFS跟踪器(Tracker)

配置文件详细说明参考:FastDFS 配置文件详解

  • 进入 /etc/fdfs,复制 FastDFS 跟踪器样例配置文件 tracker.conf.sample,并重命名为 tracker.conf。
[root@localhost fastdfs-5.11]# cd /etc/fdfs/
[root@localhost fdfs]# cp tracker.conf.sample tracker.conf
[root@localhost fdfs]#  vim tracker.conf
  • 编辑tracker.conf ,标红的需要修改下,其它的默认即可。
# 配置文件是否不生效,false 为生效
disabled=false

# 提供服务的端口
port=22122

# Tracker 数据和日志目录地址(根目录必须存在,子目录会自动创建)
base_path=/extfs/fastdfs/tracker

# HTTP 服务端口 默认8080 ,建议修改 防止冲突
http.server_port=9999
  • 创建tracker基础数据目录,即base_path对应的目录
[root@localhost fdfs]# mkdir -p /fastdfs/tracker
  • 防火墙中打开跟踪端口(默认的22122)
# vim /etc/sysconfig/iptables

添加如下端口行:
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22122 -j ACCEPT

重启防火墙:
# service iptables restart
  • 启动Tracker

初次成功启动,会在 /fdfsdfs/tracker/ (配置的base_path)下创建 data、logs 两个目录。

[root@localhost fdfs]# /etc/init.d/fdfs_trackerd start
[root@localhost fdfs]# service fdfs_trackerd start
[root@localhost fdfs]# systemctl start fdfs_trackerd
  • 查看 FastDFS Tracker 是否已成功启动
# systemctl status fdfs_trackerd  # 查看服务状态 运行状态则算成功
 fdfs_trackerd.service - LSB: FastDFS tracker server
   Loaded: loaded (/etc/rc.d/init.d/fdfs_trackerd; bad; vendor preset: disabled)
   Active: active (exited) since 四 2019-05-09 08:57:18 CST; 6min ago
     Docs: man:systemd-sysv-generator(8)
  Process: 130913 ExecStop=/etc/rc.d/init.d/fdfs_trackerd stop (code=exited, status=2)
  Process: 131030 ExecStart=/etc/rc.d/init.d/fdfs_trackerd start (code=exited, status=0/SUCCESS)

# netstat -tulnp|grep fdfs   # 22122端口正在被监听,则算是Tracker服务安装成功
   tcp        0      0 0.0.0.0:22122           0.0.0.0:*               LISTEN      27492/fdfs_trackerd 
  • 关闭Tracker命令
[root@localhost fdfs]# service fdfs_trackerd stop
[root@localhost fdfs]# systemctl stop fdfs_trackerd #centos7 推荐
[root@localhost fdfs]# /etc/init.d/fdfs_trackerd stop
  • 设置Tracker开机启动
# chkconfig fdfs_trackerd on
或
#systemctl enable fdfs_trackerd.service
或者:
# vim /etc/rc.d/rc.local
加入配置:
/etc/init.d/fdfs_trackerd start 

# 关闭开机自启是
# systemctl disable fdfs_trackerd.service
# chkconfig fdfs_trackerd off
  • tracker server 目录及文件结构

Tracker服务启动成功后,会在base_path下创建data、logs两个目录。目录结构如下:

${base_path}
|__data
| |__storage_groups.dat:存储分组信息
| |__storage_servers.dat:存储服务器列表
|__logs
| |__trackerd.log: tracker server 日志文件 

2.2.3 配置 FastDFS 存储 (Storage)

配置文件详细说明参考:FastDFS 配置文件详解

  • 进入 /etc/fdfs 目录,复制 FastDFS 存储器样例配置文件 storage.conf.sample,并重命名为 storage.conf
# cd /etc/fdfs
# cp storage.conf.sample storage.conf
# vim storage.conf
  • 编辑storage.conf

标红的需要修改,其它的默认即可。

# 配置文件是否不生效,false 为生效
disabled=false 

# 指定此 storage server 所在 组(卷)
group_name=group1

# storage server 服务端口
port=23000

# 心跳间隔时间,单位为秒 (这里是指主动向 tracker server 发送心跳)
heart_beat_interval=30

# Storage 数据和日志目录地址(根目录必须存在,子目录会自动生成)  (注 :这里不是上传的文件存放的地址,之前版本是的,在某个版本后更改了)
base_path=/extfs/fastdfs/storage

# 存放文件时 storage server 支持多个路径。这里配置存放文件的基路径数目,通常只配一个目录。
store_path_count=1


# 逐一配置 store_path_count 个路径,索引号基于 0。
# 如果不配置 store_path0,那它就和 base_path 对应的路径一样。
store_path0=/extfs/fastdfs/storage

# FastDFS 存储文件时,采用了两级目录。这里配置存放文件的目录个数。 
# 如果本参数只为 N(如: 256),那么 storage server 在初次运行时,会在 store_path 下自动创建 N * N 个存放文件的子目录。
subdir_count_per_path=256

# tracker_server 的列表 ,会主动连接 tracker_server
# 有多个 tracker server 时,每个 tracker server 写一行
tracker_server=192.168.0.200:22122
tracker_server=192.168.0.201:22122

# 允许系统同步的时间段 (默认是全天) 。一般用于避免高峰同步产生一些问题而设定。
sync_start_time=00:00
sync_end_time=23:59
# 访问端口 默认80  建议修改 防止冲突
http.server_port=9998
  • 创建Storage基础数据目录,对应base_path目录
# 对应base_path
# mkdir -p /extfs/fastdfs/storage/base
 
# 这是配置的store_path0路径,有多个要创建多个
# mkdir -p /extfs/fastdfs/storage/
  • 防火墙中打开存储器端口(默认的 23000)
# vim /etc/sysconfig/iptables

添加如下端口行:
-A INPUT -m state --state NEW -m tcp -p tcp --dport 23000 -j ACCEPT

重启防火墙:
# service iptables restart
  • 启动 Storage

启动Storage前确保Tracker是启动的。初次启动成功,会在 /fastdfs/storage/base(base_path) 目录下创建 data、 logs 两个目录。

可以用这种方式启动
# /etc/init.d/fdfs_storaged start
# service fdfs_storaged start
# systemctl start fdfs_storaged  #centos7 推荐
  • 查看 Storage 是否成功启动
# netstat -unltp|grep fdfs #23000 端口正在被监听,就算 Storage 启动成功。
tcp        0      0 0.0.0.0:23000           0.0.0.0:*               LISTEN      28834/fdfs_storaged 
# systemctl status fdfs_storaged # 查看服务状态
● fdfs_storaged.service - LSB: FastDFS storage server
   Loaded: loaded (/etc/rc.d/init.d/fdfs_storaged; bad; vendor preset: disabled)
   Active: active (running) since 四 2019-05-09 09:22:53 CST; 2s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 23015 ExecStart=/etc/rc.d/init.d/fdfs_storaged start (code=exited, status=0/SUCCESS)
    Tasks: 1
   Memory: 184.0K
   CGroup: /system.slice/fdfs_storaged.service
           └─23023 /usr/bin/fdfs_storaged /etc/fdfs/storage.conf
 
5月 09 09:22:53 localhost.localdomain systemd[1]: Starting LSB: FastDFS storage server...
5月 09 09:22:53 localhost.localdomain fdfs_storaged[23015]: Starting FastDFS storage server:
5月 09 09:22:53 localhost.localdomain systemd[1]: Started LSB: FastDFS storage server.
  • 关闭Storage
[root@localhost fdfs]# service fdfs_storaged stop
[root@localhost fdfs]# systemctl stop fdfs_storaged #centos7 推荐
[root@localhost fdfs]# /etc/init.d/fdfs_storaged stop
  • 查看Storage和Tracker是否在通信:
# /usr/bin/fdfs_monitor /etc/fdfs/storage.conf
[2019-05-09 11:34:09] DEBUG - base_path=/fastdfs/storage/base, connect_timeout=30, network_timeout=60, tracker_server_count=2, anti_steal_token=0, anti_steal_secret_key length=0, use_connection_pool=0, g_connection_pool_max_idle_time=3600s, use_storage_id=0, storage server id count: 0
 
server_count=2, server_index=0
 
tracker server is 192.168.0.200:22122
 
group count: 1
 
Group 1:
group name = group1
disk total space = 51175 MB
disk free space = 14251 MB
trunk free space = 0 MB
storage server count = 2
active server count = 1
storage server port = 23000
storage HTTP port = 9888
store path count = 1
subdir count per path = 256
current write server index = 0
current trunk file id = 0
 
    Storage 1:
        id = 192.168.0.200
        ip_addr = 192.168.0.200 (localhost.localdomain)  ACTIVE
        。。。
     Storage 2:
        id = 192.168.0.201
        ip_addr = 192.168.0.201  WAIT_SYNC
  • 设置 Storage 开机启动
# chkconfig fdfs_storaged on
# chkconfig fdfs_storaged on  
或
#systemctl enable fdfs_storaged.service  (推荐)
或者:
# vim /etc/rc.d/rc.local
加入配置:
/etc/init.d/fdfs_storaged  start 

关闭开机自启
# systemctl disable fdfs_storaged.service
# chkconfig fdfs_storaged off
  • Storage 目录

同 Tracker,Storage 启动成功后,在base_path 下创建了data、logs目录,记录着 Storage Server 的信息。
在 store_path0/data 目录下,创建了N*N个子目录:

[root@localhost ~]# ls /extfs/fastdfs/storage/data/
00  05  0A  0F  14  19  1E  23  28  2D  32  37  3C  41  46  4B  50  55  5A  5F  64  69  6E  73  78  7D  82  87  8C  91  96  9B  A0  A5  AA  AF  B4  B9  BE  C3  C8  CD  D2  D7  DC  E1  E6  EB  F0  F5  FA  FF
01  06  0B  10  15  1A  1F  24  29  2E  33  38  3D  42  47  4C  51  56  5B  60  65  6A  6F  74  79  7E  83  88  8D  92  97  9C  A1  A6  AB  B0  B5  BA  BF  C4  C9  CE  D3  D8  DD  E2  E7  EC  F1  F6  FB
02  07  0C  11  16  1B  20  25  2A  2F  34  39  3E  43  48  4D  52  57  5C  61  66  6B  70  75  7A  7F  84  89  8E  93  98  9D  A2  A7  AC  B1  B6  BB  C0  C5  CA  CF  D4  D9  DE  E3  E8  ED  F2  F7  FC
03  08  0D  12  17  1C  21  26  2B  30  35  3A  3F  44  49  4E  53  58  5D  62  67  6C  71  76  7B  80  85  8A  8F  94  99  9E  A3  A8  AD  B2  B7  BC  C1  C6  CB  D0  D5  DA  DF  E4  E9  EE  F3  F8  FD
04  09  0E  13  18  1D  22  27  2C  31  36  3B  40  45  4A  4F  54  59  5E  63  68  6D  72  77  7C  81  86  8B  90  95  9A  9F  A4  A9  AE  B3  B8  BD  C2  C7  CC  D1  D6  DB  E0  E5  EA  EF  F4  F9  FE

2.2.4 上传测试

  • 修改 Tracker 服务器中的客户端配置文件
# cd /etc/fdfs
# cp client.conf.sample client.conf
# vim client.conf
  • 修改如下配置即可,其它默认
# Client 的数据和日志目录
base_path=/extfs/fastdfs/client
 
# Tracker端口
tracker_server=192.168.0.200:22122
  • 上传测试

    在linux内部执行如下命令上传 namei.jpeg 图片

# /usr/bin/fdfs_upload_file /etc/fdfs/client.conf namei.jpeg

上传成功后返回文件ID号:group1/M00/00/00/wKgz6lnduTeAMdrcAAEoRmXZPp870.jpeg

返回的文件ID由group、存储目录、两级子目录、fileid、文件后缀名(由客户端指定,主要用于区分文件类型)拼接而成。

image-20210504171440255

2.3 Nginx 安装和配置

上面将文件上传成功了,但我们无法下载。因此安装Nginx作为服务器以支持Http方式访问文件。同时,后面安装FastDFS的Nginx模块也需要Nginx环境。

Nginx只需要安装到StorageServer所在的服务器即可,用于访问文件

Nginx 的安装分为两个步骤:

  • 安装 Nginx

安装nginx 参见:https://blog.csdn.net/prcyang/article/details/90032781

# vim /usr/local/nginx/conf/nginx.conf
配置如下
server {
        listen       8081;
        server_name  192.168.0.200;
 
        location /group1/M00{
        alias /fastdfs/storage/data/;
         autoindex on;
 
       }
 
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
        root   html;
       }
    }

在浏览器访问之前上传的图片 http://192.168.0.200:8081/group1/M00/00/00/wKgz6lnduTeAMdrcAAEoRmXZPp870.jpeg

2.4 FastDFS 配置 Nginx 模块

FastDFS 通过 Tracker 服务器,将文件放在 Storage 服务器存储, 但是同组存储服务器之间需要进行文件复制, 有同步延迟的问题。

  假设 Tracker 服务器将文件上传到了 192.168.51.128,上传成功后文件 ID已经返回给客户端。

  此时 FastDFS 存储集群机制会将这个文件同步到同组存储 192.168.51.129,在文件还没有复制完成的情况下,客户端如果用这个文件 ID 在 192.168.51.129 上取文件,就会出现文件无法访问的错误。

  而 fastdfs-nginx-module 可以重定向文件链接到源服务器取文件,避免客户端由于复制延迟导致的文件无法访问错误。

#cd /usr/local/src
# 这里可以直接把下载好的上传后解压
#wget -O fastdfs-nginx-module-1.20.tar.gz  https://codeload.github.com/happyfish100/fastdfs-nginx-module/tar.gz/V1.20
# tar -zxvf fastdfs-nginx-module-1.20.tar.gz 

vim /usr/local/src/fastdfs-nginx-module-1.20/src/config
修改为如下内容

img

改变的文件内容

  • 配置nginx,添加fastdfs-nginx-module 模块 (注意如果已经安装过nginx,那么先nginx/sbin/nginx -V看下原本的配置)
# 先停掉nginx服务 如果没有配置为服务 则使用 # /usr/local/nginx/sbin/nginx -s stop
# systemctl stop nginx     
#进入nginx源码目录
# cd /usr/local/src/nginx-1.16.0/   
#添加fastdfs-nginx-module 模块
#[root@localhost nginx-1.16.0]#./configure  --add-module=/usr/local/src/fastdfs-nginx-module-1.20/src
#重新编译安装nginx
#[root@localhost nginx-1.16.0]# make
#[root@localhost nginx-1.16.0]# make install
 
#验证是否加载fastdfs-nginx-module模块是否 ,有如下标红部分表示成功
# /usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.16.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC) 
configure arguments: --add-module=/usr/local/src/fastdfs-nginx-module-1.20/src
  • 复制 fastdfs-nginx-module 源码中的配置文件 mod_fastdfs.conf 到/etc/fdfs 目录, 并修改
# cp /usr/local/src/fastdfs-nginx-module-1.20/src/mod_fastdfs.conf /etc/fdfs/
 修改如下配置,其它默认
 
base_path=/extfs/fastdfs/storage
 # 连接超时时间
connect_timeout=10
 
# Tracker Server
tracker_server=192.168.0.200:22122
tracker_server=192.168.0.201:22122
 
# StorageServer 默认端口
storage_server_port=23000
 
# 如果文件ID的uri中包含/group**,则要设置为true
url_have_group_name = true
 
# Storage 配置的store_path0路径,必须和storage.conf中的一致
store_path0=/extfs/fastdfs/storage
  • 复制 FastDFS 的部分配置文件到/etc/fdfs 目录
#cd /extfs/software/fastdfs/fastdfs-5.11/conf/  #解压的fastdfs的目录下的conf,如果存在就不需要拷贝
[root@localhost conf]# cp anti-steal.jpg http.conf mime.types /etc/fdfs/
  • 配置nginx,修改nginx.conf
# vim /usr/local/nginx/conf/nginx.conf
修改配置,其它的默认
在80端口下添加fastdfs-nginx模块
location ~/group([0-9])/M00 {
    ngx_fastdfs_module;
}

完整配置如下 供参考

user root;
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
 
    server {
 
        listen      9888 ;
        server_name  192.168.0.200;
       # location /group1/M00{
         # alias /fastdfs/storage/data/;
        # autoindex on;
       #}
 location ~/group[0-9]/ {
                ngx_fastdfs_module;
            }
 
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
        root   html;
       }
    }
 
}

注意:

  listen 9888端口值是要与 /etc/fdfs/storage.conf 中的 http.server_port=9888 (前面改成9888了)相对应。如果改成其它端口,则需要统一,同时在防火墙中打开该端口。

  location 的配置,如果有多个group则配置location ~/group([0-9])/M00 ,没有则不用配group。

在 /fastdfs/storage 文件存储目录下创建软连接,将其链接到实际存放数据的目录,这一步可以省略。

ln -s /fastdfs/storage/data/ /fastdfs/storage/data/M00

启动nginx

# systemctl start nginx

在地址栏访问。

能下载文件就算安装成功。注意和之前直接使用nginx路由访问不同的是,这里配置 fastdfs-nginx-module 模块,可以重定向文件链接到源服务器取文件。

2.5 最终部署结构图(参考)

3、应用

基于maven项目,或者直接springboot快速搭建项目!

3.1 依赖

<!--fastDFS -->
<dependency>
    <groupId>com.github.tobato</groupId>
    <artifactId>fastdfs-client</artifactId>
    <version>1.26.5</version>
        <exclusions>
            <exclusion>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<!-- commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>

3.2 配置

# fastDFS
fdfs:
  so-timeout: 2000
  connect-timeout: 1000
  # dev
  webServerUrl: http://192.168.56.101:80/ # ngxin地址,查看图片地址
  thumb-image:             #缩略图生成参数
    width: 150
    height: 150
  tracker-list:            #TrackerList参数,支持多个
    # dev
    - 192.168.56.101:22122
  pool:
    #从池中借出的对象的最大数目(配置为-1表示不限制)
    max-total: -1
    #获取连接时的最大等待毫秒数(默认配置为5秒)
    max-wait-millis: 5000
    #每个key最大连接数
    max-total-per-key: 50
    #每个key对应的连接池最大空闲连接数
    max-idle-per-key: 10
    #每个key对应的连接池最小空闲连接数
    max_idle_per_key: 5

3.3 统一工具

FastDFSClient.java

@Configuration
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
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 文件url
     * @return
     */
    public byte[]  download(String fileUrl) {
        String group = fileUrl.substring(0, fileUrl.indexOf("/"));
        String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
        byte[] bytes = storageClient.downloadFile(group, path, new DownloadByteArray());
        return bytes;
    }

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

    private String removeResAccessUrl(String imgUrl) {
        return imgUrl.replace(fdfsWebServer.getWebServerUrl(),"");
    }

    public String uploadHcImageFile(byte[] buff, String fileName) {
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath storePath = storageClient.uploadFile(stream, buff.length, FilenameUtils.getExtension(fileName),null);
        return storePath.getFullPath();
    }
}

3.4 服务

IFastDFSService.java****

public interface IFastDFSService {
    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    Result<BsFiles> uploadFiles(MultipartFile file);
}

FastDFSServiceImpl.java

@Slf4j
@Service
public class FastDFSServiceImpl implements IFastDFSService {

    @Autowired
    FastDFSClient fastDFSClient;
    @Autowired
    FilesMapper filesMapper;
    public static final Long MAX_SIZE = 10485760L;
    @Autowired
    private FdfsWebServer fdfsWebServer;

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @Override
    public Result<BsFiles> uploadFiles(MultipartFile file){
        log.info("fastDFS uploadFiles file->{}", file);
        try {
            //1.判断文件大小,文件过大使用断点续传的方式
            if (file.getSize() > MAX_SIZE) {
                return Results.newFailResult(ErrorCode.FILE_ERROR, "文件过大,请使用大文件传输");
            }
            //1.获取源文件基本信息
            String fileName = file.getOriginalFilename();
            if (EmptyUtils.basicIsEmpty(fileName)) {
                return Results.newFailResult(ErrorCode.FILE_ERROR, "文件名不能为空");
            }
            //3.文件后缀
            String suffixName = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".")) : null;

            //4.文件上传
            String url = fastDFSClient.uploadFile(file);

            //5.保存文件信息
            BsFiles files = new BsFiles().setFilePath(url.replace(fdfsWebServer.getWebServerUrl(),""))
                    .setFileName(fileName)
                    .setSuffix(suffixName == null ? null : suffixName.substring(1))
                    .setFullFilePath(url);
            log.info("fastDFS uploadFiles files->{}", files);
            filesMapper.insert(files);

            //6.返回信息
            return Results.newSuccessResult(files);
        }catch (Exception e){
            log.error("上传协议文件出错", e);
        }
        return Results.newFailResult(ErrorCode.FILE_ERROR, "上传失败");
    }
}

3.5 对外接口

FastDFSController.java

@Slf4j
@RestController
@RequestMapping("/fastdfs")
@RequiredArgsConstructor
public class FastDFSController {
    private static final Logger logger = LoggerFactory.getLogger(FastDFSController.class);

    @Autowired
    IFastDFSService fastDFSService;

    @PostMapping("/uploadFile")
    public RestResponse<BsFiles> uploadFile(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
            return RestResponses.newFailResponse(ErrorCode.INVALID_PARAMETER, "文件不能为空");
        }
        return RestResponses.newResponseFromResult(fastDFSService.uploadFiles(file));
    }
}

3.6 PostMan测试

上传测试:

image-20210504222351557

结果:

image-20210504223901069

4、常用命令

4.1 FastDFS

查找进程
ps -ef | grep fdfs

停止tracker和storage
/usr/local/fastdfs-5.05/stop.sh  /etc/fdfs/storage.conf
/usr/local/fastdfs-5.05/stop.sh  /etc/fdfs/tracker.conf

编辑配置文件
vim /etc/fdfs/storage.conf
vim /etc/fdfs/tracker.conf

启动tracker和storage
/usr/bin/fdfs_trackerd /etc/fdfs/tracker.conf
/usr/bin/fdfs_storaged /etc/fdfs/storage.conf

重启tracker和storage
/usr/local/fastdfs-5.05/restart.sh /usr/bin/fdfs_trackerd /etc/fdfs/tracker.conf
/usr/local/fastdfs-5.05/restart.sh /usr/bin/fdfs_storaged /etc/fdfs/storage.conf

监控状态
fdfs_monitor /etc/fdfs/storage.conf

开机自启与关闭
# systemctl enable fdfs_trackerd.service
# systemctl disable fdfs_trackerd.service
或
# chkconfig fdfs_trackerd off
# chkconfig fdfs_trackerd on

# systemctl enable fdfs_storaged.service
# systemctl disable fdfs_storaged.service
或
# chkconfig fdfs_storaged off
# chkconfig fdfs_storaged on

文件上传
fdfs_test /etc/fdfs/client.conf upload /root/图片/zidana.jpg

4.2 Nginx

#绝对路径方式管理服务
$ /usr/local/nginx/sbin/nginx   启动服务
$ /usr/local/nginx/sbin/nginx -s reload  重新加载服务
$ /usr/local/nginx/sbin/nginx -s stop    停止服务


1.ps  aux | grep nginx 查看nginx运行状态

2.systemctl  start  nginx.service  启动nginx

3.nginx -s stop  立即停止nginx服务

4.nginx -s quit  从容停止

5.kill all  nginx 杀死所有的nginx 进程

6.systemctl   stop nginx.service  停止nginx服务器

7.systemctl   restart  ngnix.service  重启nginx服务器

8.nginx  -s  reload   重新载入配置文件文件

二、文件位置

1.rpm  -ql  nginx    查看nginx安装列表,可以看到nginx所有的安装位置

2.总配置文件:/etc/nginx/nginx.conf

3./etc/nginx/conf.d  所有的nginx自定义配置文件

4./var/log/nginx/error.log  错误日志文件

5./usr/share/nginx/html   服务器默认启动目录

4.3 需要注意的点

注意点:

我们要是使用终止命令或者使用 kill -9 fdfs进程id 来终结fdfs_storaged服务的,然后用上面的启动命令是启动不了的,因为log日志问题,会出现下面的错误

img

一般在我们跟换ip地址的时候,重启fdfs服务,就使用重启命令就行。

查看服务启动:

ps -ajx|grep fdfs

以及注意防火墙是否开启

systemctl stop firewalld.server

5.权限与Nginx

主要针对两个问题:

  • 原本服务器已经存在Nginx,如何添加新fastdfs-nginx-module,编译新的Nginx并启动
  • 关于root安装的fastdfs如何给普通用户权限

5.1 服务器存在Nginx添加新模块

一般按照Nginx解压源码在/usr/local下,注意我这边解压的插件也在同目录下方便查找

image-20210510161521500

  • 查看已安装的nginx的配置,并复制记录(图中最末尾原本是不存在--add-module=/usr/local/fastdfs-nginx-module/src,我这边展示我已经安装好了的)
# /extfs/nginx/sbin/nginx -V 

image-20210510161713243

  • 在源码中进行配置并编译(注意编译需要root用户下进行)
进入源码地址
# cd /usr/local/nginx-1.16.1/
复制上面的配置,并加上fastdfs-nginx-module的地址(--add-module=/usr/local/fastdfs-nginx-module/src)
# ./configure --prefix=/extfs/nginx --sbin-path=/extfs/nginx/sbin/nginx --conf-path=/extfs/nginx/conf/nginx.conf --error-log-path=/extfs/nginx/log/error.log --http-log-path=/extfs/nginx/log/access.log --pid-path=/var/run/nginx/nginx.pid --lock-path=/var/lock/nginx.lock --user=admin --group=admin --with-http_dav_module --with-http_v2_module --with-http_ssl_module --with-http_flv_module --with-http_sub_module --with-http_mp4_module --with-http_auth_request_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_gunzip_module --with-http_realip_module --with-http_addition_module --with-pcre --with-mail --with-mail_ssl_module --with-file-aio --with-threads --with-stream --with-stream_ssl_module --add-module=/usr/local/headers-more-nginx-module-master --add-module=/usr/local/fastdfs-nginx-module/src  
编译
# make
  • 编译后会在objs下,拷贝它到原本的nginx执行目录下(注意备份一下/extfs/nginx/sbin/原本的nginx)

image-20210510162411435

复制(注意备份一下/extfs/nginx/sbin/原本的nginx)
# cp /usr/local/nginx-1.16.1/objs/nginx /extfs/nginx/sbin/

进入/extfs/nginx/sbin/ 修改nginx执行权限给怕普通用户
#cd /extfs/nginx/sbin/ 
#setfacl -m u:admin:r-x nginx
验证
#/extfs/nginx/sbin/nginx -V 
后面有--add-module=/usr/local/fastdfs-nginx-module/src就表示成功了
  • 配置文件照上面一样添加在/extfs/nginx/conf/nginx.conf

5.2 root安装的fastdfs给普通用户启动权限

主要是为了安全,给普通用户执行权限即可。

注意: 首先需要关闭目前已经启动的fastdfs,如果你设置了自启动,也需要关闭,因为自启动是root用户

主要用到的命令是

#修改文件夹操作人
chown admin:admin -R 文件夹名称

修改的地方有

  • /etc/fdfs #主要配置的地方,结果如下

image-20210510163323549

  • /extfs/fastdfs 配置文件中的存储目录

image-20210510163402546

  • 注意上传一下启动脚本,便于普通用户启动
上传完脚本,可能没有执行权限,给一下执行权限
# chmod 764 start_fastdfs_storaged.sh
# chmod 764 start_fastdfs_trackerd.sh

结果如下:

image-20210510163501453

  • 之后就可以以admin普通用户去启动fastdfs了


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM