FastDFS安装 +SpringBoot Demo

FastDFS 是一个开源的轻量级 分布式文件系统 ,它对文件进行管理,功能包括:文件存储、文件同步、

文件访问(文件上传、文件下载)等,解决了大容量存储和负载均衡的问题。特别适合以文件为载体的
在线服务,如相册网站、视频网站等等

1、原始安装(相关软件下载FastDfs-原生安装-全套安装包.zip-Java文档类资源-CSDN下载)

  1. 环境准备:两台centos7.x的虚拟机,一台作为Tracker,一台作为Storage(也可以在一台服务器上,同时作为Tracker和Storage。本案例是两台服务器)
  2. 两台虚拟机都要执行命令安装编译环境
    yum install git gcc gcc-c++ make automake autoconf libtool pcre pcre-devel zlib zlib-devel openssl-devel wget vim -y
  3. 两台虚拟机的磁盘目录
    说明位置
    所有安装包/usr/local/src
    数据存储位置

    /home/dfs/

  4. 安装libfastcommon
    1. 下载libfastcommon资源包
      git clone https://github.com/happyfish100/libfastcommon.git --depth 1
      

      由于github的网速比较慢,这里提供了已经下载的资源包(最下方的连接里),资源包分别上传到两台虚拟机并解压

    2. 进入到libfastcommon目录,编译安装
      cd libfastcommon/
      #编译安装
      ./make.sh && ./make.sh install 

  5. 机安装FastDFS
    1. 下载资源包名编译安装
      #方法一 :使用gitbub
      cd ../ #返回上一级目录
      git clone https://github.com/happyfish100/fastdfs.git --depth 1
      cd fastdfs/
      ./make.sh && ./make.sh install #编译安装
      
      #方法二 :使用安装包
      cd ../ #返回上一级目录
      上传fastdfs.tar.gz(资源在最下面的连接里)
      tar zxvf fastdfs.tar.gz
      cd fastdfs/
      ./make.sh && ./make.sh install #编译安装

    2. 配置文件准备

      #注意:
          1、如果tracker和storage是在两台服务器需要
              #在tracker虚拟机上执行
              cp /etc/fdfs/tracker.conf.sample /etc/fdfs/tracker.conf
              #在storage虚拟机上执行
              cp /etc/fdfs/storage.conf.sample /etc/fdfs/storage.conf
             如果tracker和storage是在一台服务器就需要在同一台服务器执行
              cp /etc/fdfs/tracker.conf.sample /etc/fdfs/tracker.conf
              cp /etc/fdfs/storage.conf.sample /etc/fdfs/storage.conf
      2、修改配置文件tracker.conf
         vim /etc/fdfs/tracker.conf
          port端口号,根据需要是否修改,默认是22122
          base_path路径需要修为base_path=/home/dfs
      
      3、修改配置文件storage.conf
         vim /etc/fdfs/storage.conf
          port端口号,根据需要是否修改,默认是23000
          base_path路径需要修为base_path=/home/dfs
          store_path0虚拟目录为store_path0=/home/dfs
              注意:若store_path_count=2,就需要加一个store_path1=/home/dfs2依次类推
          tracker_server的IP地址和端口需要修改为自己tracker服务器的地址和端口
      
      

      启动防火墙

    3. 启动tracker和storage

      #不关闭防火墙的话无法使用
      systemctl stop firewalld.service #关闭
      systemctl restart firewalld.service #重启
      
      #启动tracker服务
      /etc/init.d/fdfs_trackerd start
      
      #启动storage
      /etc/init.d/fdfs_storaged start 
      
      
      注意:tracker和storage启动时在各自的服务上启动,否则启动时会报错
      
      
      #查看服务是否启动
      netstat -ntlp|grep fdfs
      (如果未安装,可执行 yum install net-tools )

      其他命令

      /etc/init.d/fdfs_trackerd start #启动tracker服务
      /etc/init.d/fdfs_trackerd restart #重启动tracker服务
      /etc/init.d/fdfs_trackerd stop #停止tracker服务
      chkconfig fdfs_trackerd on #自启动tracker服务
      /etc/init.d/fdfs_storaged start #启动storage服务
      /etc/init.d/fdfs_storaged restart #重动storage服务
      /etc/init.d/fdfs_storaged stop #停止动storage服务
      chkconfig fdfs_storaged on #自启动storage服务
      
  6. client测试
    #在storage服务器中执行命令 
    #1、复制客户端文件,测试用
    cp /etc/fdfs/client.conf.sample /etc/fdfs/client.conf 
    
    #2、修改/etc/fdfs/client.conf的配置
    vim /etc/fdfs/client.conf
        修改base_path=/home/dfs
        修改tracker_server为自己tracker的ip地址和端口号
    #3、测试上传文件
        #创建一个abc.txt文件
             echo 123456 > abc.txt
        #上传abc.txt文件
            fdfs_upload_file /etc/fdfs/client.conf ./abc.txt
    
    

  7. 查看上传的文件

    group1/M00/00/00/wKgff2JhDcSACNnEAAAAB_cq_GM621.txt
    #其中group1是组
    #M00是虚拟目录,由前面步骤指定虚拟目录为/home/dfs/data

  8. 在storage服务器上 安装fastdfs-nginx-module 与nginx
    #下载安装包fastdfs-nginx-module
    
    #1.切到目录
    cd /usr/local/src
    
    #2.git下载安装包比较慢,提供已下载的安装包在最下方连接里,解压后把文件上传到该目录下
    git clone https://github.com/happyfish100/fastdfs-nginx-module.git --depth 1
    
    #3.若上传的是安装包需要解压
    tar -zxvf nginx-module.tar.gz 
    
    #4.修改fastdfs-nginx-module/src/config文件(否则编译时会提示致命错误commons....)
    vim fastdfs-nginx-module/src/config
        #找到对应位置修改
        ngx_module_incs="/usr/include/fastdfs /usr/include/fastcommon/"
        CORE_INCS="$CORE_INCS /usr/include/fastdfs /usr/include/fastcommon/"
    
    
    #5.下载安装包nginx 也可以使用提供的安装包
    wget http://nginx.org/download/nginx-1.15.4.tar.gz
    
    #6.解压安装包
    tar -zxvf nginx-1.15.4.tar.gz
    
    #7.进入nginx-1.15.4目录
    cd nginx-1.15.4/
    
    #8.添加fastdfs-nginx-module模块
    ./configure --add-module=/usr/local/src/fastdfs-nginx-module/src/
    
    #9.编译安装(如果上面第4步没有修改,会报错)
    make && make install
    
    #拷贝配置文件
    cp /usr/local/src/fastdfs-nginx-module/src/mod_fastdfs.conf /etc/fdfs
    
    cd /usr/local/src/
    
    #根据自己本地目录进入
    cd fastdfs/conf 或 cd fastdfs-5.11/conf    
    
    #复制文件 供nginx访问使用
    cp http.conf /etc/fdfs/
    cp mime.types /etc/fdfs/

     #1、修改mod_fastdfs.conf的配置文件
    vim /etc/fdfs/mod_fastdfs.conf
    
    修改3个地方
    store_path0=/home/dfs
    tracker_server=192.168.31.129:22122 #对应自己tracker的ip和端口
    url_have_group_name = true
    
    
     #2、修改nginx.conf的配置文件
    vim /usr/local/nginx/conf/nginx.conf
    
    #添加如下配置
    server {
        listen       8888;    ## 该端口为storage.conf中的http.server_port相同
        server_name  192.168.31.127; ## storage的ip地址
        location ~/group[0-9]/ {
            ngx_fastdfs_module;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
        root   html;
        }
    }

  9. 启动nginx
    #启动nginx
    /usr/local/nginx/sbin/nginx
    
    #查看是否启动成功
    ps aux|grep nginx
    
    
    
    相关操作
    /usr/local/nginx/sbin/nginx #启动nginx
    /usr/local/nginx/sbin/nginx -s reload #重启nginx
    /usr/local/nginx/sbin/nginx -s stop #停止nginx

  10. 通过浏览器访问上传的文件
    #本地中有一张图片tp.jpg,切换到目录
    cd /root/Pictures
    
    #执行上传图片命令
    fdfs_upload_file /etc/fdfs/client.conf ./tp.jpg 
    
    #上传文件成功后生成的图片地址
    group1/M00/00/00/wKgff2JkDzGAM2L3AACGRGUIV7E164.jpg
    
    
    #浏览器访问刚刚上传图片 访问地址http://本地ip:8888/图片路径
    http://192.168.31.127:8888/group1/M00/00/00/wKgff2JkDzGAM2L3AACGRGUIV7E164.jpg
    
    
    #上传文档、视频、图片都可以用此方法查看
    

     

     以上是原始的安装方法,适合在生成和测试环境上使用,官方安装文档连接https://github.com/happyfish100/fastdfs/wiki

         相关安装包资源链接FastDfs-原生安装-全套安装包.zip-Java文档类资源-CSDN下载

2、Docker安装(适用于自己做测试时使用)

  1. 新增一个目录FastDfas,在目录中新增docker-compose.yml文件
    #创建目录
    mldir FastDFS
    #进入目录
    cd FastDFS
    #进入文件编辑页
    vim docker-compose.yml
    
    #输入内容如下,注意空格关系
    version: '2'
    services:
        fastdfs-tracker:
            hostname: fastdfs-tracker
            container_name: fastdfs-tracker
            image: season/fastdfs:1.2
            network_mode: "host"
            command: tracker
            volumes:
              - ./tracker_data:/fastdfs/tracker/data
        fastdfs-storage:
            hostname: fastdfs-storage
            container_name: fastdfs-storage
            image: season/fastdfs:1.2
            network_mode: "host"
            volumes:
              - ./storage_data:/fastdfs/storage/data
              - ./store_path:/fastdfs/store_path
            environment:
              - TRACKER_SERVER=192.168.31.130:22122
            command: storage
            depends_on:
              - fastdfs-tracker
        fastdfs-nginx:
            hostname: fastdfs-nginx
            container_name: fastdfs-nginx
            image: season/fastdfs:1.2
            network_mode: "host"
            volumes:
              - ./nginx.conf:/etc/nginx/conf/nginx.conf
              - ./store_path:/fastdfs/store_path
            environment:
              - TRACKER_SERVER=192.168.31.130:22122
            command: nginx
    
    
    #保存上面文件,TRACKER_SERVER对应的IP地址及端口号,对应服务的ip地址和端口号,默认本地ip

  2. 在FastDFS中新增nginx.conf文件
    #vim nginx.conf
    
    #输入内容如下:
    #user  nobody;
    worker_processes  1;
    
    #error_log  logs/error.log;
    #error_log  logs/error.log  notice;
    #error_log  logs/error.log  info;
    
    #pid        logs/nginx.pid;
    
    events {
    	worker_connections  1024;
    }
    
    http {
    	include       mime.types;
    	default_type  application/octet-stream;
    
    	#log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    	#                  '$status $body_bytes_sent "$http_referer" '
    	#                  '"$http_user_agent" "$http_x_forwarded_for"';
    
    	#access_log  logs/access.log  main;
    
    	sendfile        on;
    	#tcp_nopush     on;
    
    	#keepalive_timeout  0;
    	keepalive_timeout  65;
    
    	#gzip  on;
    
    	server {
    		listen       10021;
    		server_name  localhost;
    
    		#charset koi8-r;
    
    		#access_log  logs/host.access.log  main;
    
    		# 修改部分
    		location / {
    			root /fastdfs/store_path/data;
    			ngx_fastdfs_module;
    		}
    
    		#error_page  404              /404.html;
    
    		# redirect server error pages to the static page /50x.html
    		#
    		error_page   500 502 503 504  /50x.html;
    		location = /50x.html {
    			root   html;
    		}
    	}
    }
    

  3. 启动docker-compose
    #在FastDFS目录下启动docker-compose
    
    docker-compose up -d
    
    #如果是第一次启动,时间比较久,因为需要去拉取镜像文件
    # -d表示后台启动,不加-d也可以

  4. 查看是否启动成功
    #查看运行容器
    docker ps 
    

3、实现代码连接FastDFS的demo

  1. 框架是是pringboot+html
  2. 需要引入的依赖
            <dependency>
                <groupId>com.github.tobato</groupId>
                <artifactId>fastdfs-client</artifactId>
                <version>1.26.4</version>
            </dependency>
            <!-- thymeleaf依赖 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>

  3. application.properties
    fdfs.so-timeout=3000
    fdfs.connect-timeout= 1000
    fdfs.thumb-image.width=60
    fdfs.thumb-image.height= 60
    #安装tracker的ip地址
    fdfs.tracker-list=192.168.31.130:22122

  4. java代码 
    //===============1、DfsConfig配置类======================
    
    import com.github.tobato.fastdfs.FdfsClientConfig;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.EnableMBeanExport;
    import org.springframework.context.annotation.Import;
    import org.springframework.jmx.support.RegistrationPolicy;
    
    @Configuration
    @Import(FdfsClientConfig.class)
    //重复注册bean的问题
    @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
    public class DfsConfig {
    }
    
    
    //===================2、FastDFSTest测试类=================
    
    import com.github.tobato.fastdfs.domain.StorePath;
    import com.github.tobato.fastdfs.service.FastFileStorageClient;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.servlet.http.HttpServletRequest;
    import java.io.IOException;
    
    /**
     * @author 陈款
     * @since 2022/4/24
     */
    @Controller
    public class FastDFSTest {
        private static final Logger logger = LoggerFactory.getLogger(FastDFSTest.class);
    
        @Autowired
        private FastFileStorageClient storageClient;
    
        /**
         * 进入首页
         * @return
         */
        @RequestMapping("index")
        public String index(){
            return "index";
        }
    
        @RequestMapping("upload")
        @ResponseBody
        public String upload(MultipartFile multipartFile,HttpServletRequest request) throws IOException {
            String originalFilename = multipartFile.getOriginalFilename().
                    substring(multipartFile.getOriginalFilename().
                            lastIndexOf(".") + 1);
            StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(
                    multipartFile.getInputStream(),
                    multipartFile.getSize(), originalFilename, null);
            logger.info("文件路径{}",storePath.getFullPath());
            return "success";
        }
    
    
    }

  5. html代码,注意页面代码在resources->templates->index.html
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <head>
        <meta charset="UTF-8">
        <title>测试</title>
    </head>
    <body>
        <input type="file" style="height: 200px;width: 200px" name="multipartFile" id="FileUpload">
        <button style="width: 50px">提交</button>
    </body>
    
    <script type="text/javascript">
        $(document).ready(function(){
            $("button").click(function(){
                var file = document.getElementById("FileUpload").files[0];
                var needFile = new FormData()
                needFile.append("multipartFile",file)
                console.log(file);
                $.ajax(
                    {
                        url:"upload",
                        data: needFile,
                        type: 'post',
                        dataType: 'json',
                        processData : false,
                        contentType : false,
                        success:function(result)
                        {
    
                        }
                    }
                );
            });
        });
       </script>
    </html>

  6. 代码层级,以及运行的结果文件路径为group1/M00/00/00/wKgfgmJkioKAUubnAACBj38zqzA988.jpg
  7. 上传图片并测试查看图片,访问上传图片访问地址为 http:IP:端口/上传文件生成的路径. 由于docker的ip为192.168.31.130,nginx.conf配置的端口是10021,上传文件生成的路径为group1/M00/00/00/wKgfgmJkioKAUubnAACBj38zqzA988.jpg,所有访问路径为:http:192.168.31.130:10021/group1/M00/00/00/wKgfgmJkioKAUubnAACBj38zqzA988.jpg

错误总结:

  • 提示  无法获取服务端连接资源:找不到可用的tracker /192.168.31.130:22122“ 是服务器防火墙没有关闭的原因,关闭防火墙的命令:
    • systemctl stop firewalld.service           #停止firewall
    • systemctl disable firewalld.service        #禁止firewall开机启动

如果大家在搭建过程中遇到什么问题,可以发出来一起解决...

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值