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