美文网首页Linux
Centos7.x 搭建FastDFS并通过Nginx配置htt

Centos7.x 搭建FastDFS并通过Nginx配置htt

作者: dev_winner | 来源:发表于2021-03-19 22:15 被阅读0次
    • 本文有关依赖包汇总下载链接:点我去下载 ,提取码:xhy7

    FastDFS及其架构的简介:

    • FastDFS:是一个开源的分布式文件系统,用 C 语言实现,它对文件进行管理,功能包括:文件存储、文件同步、文件访问(文件上传、文件下载)等,解决了大容量存储和负载均衡的问题。特别适合以文件为载体的在线服务,如相册网站、视频网站等等。
    • FastDFS服务端有两个角色:跟踪器(tracker)和存储节点(storage)。
      • 跟踪器(tracker)用来追踪文件,相当于是文件的一个索引。
      • 存储节点(storage)用于存储文件,包括文件和文件属性(meta data)都保存到存储服务器磁盘上,完成文件管理的所有功能:文件存储、文件同步和提供文件访问等。上传文件的文件最终保存在Storage上,文件的元数据信息保存在Tracker上,通过Tracker可以实现对Storage的负载均衡。
      • Storage 一般会搭建成集群,一个 Storage Cluster 可以由多个组构成,不同的组之间不进行通信,一个组又相当于一个小的集群,组由多个 Storage Server 组成,组内的 Storage Server 会通过连接进行文件同步来保证高可用。

    Centos7.x 安装FastDFS 的步骤如下:

    • 安装 gcc 环境:yum install gcc-c++
    • 安装依赖库libeventyum -y install libevent
    • 安装依赖库libfastcommon,将下载好的libfastcommon-1.0.36.tar.gz压缩包拷贝到/usr/local/目录下,然后依次执行如下命令:
    cd /usr/local
    tar -zxvf libfastcommon-1.0.36.tar.gz
    cd libfastcommon-1.0.36
    ./make.sh
    ./make.sh install
    
    • 注意:Tracker 和 Storage 是相同的安装包,即为提供的fastdfs-5.11.tar.gz压缩包,将其拷贝至/usr/local/目录下,然后依次执行如下命令安装:
    cd /usr/local
    tar -zxvf fastdfs-5.11.tar.gz
    cd fastdfs-5.11
    ./make.sh
    ./make.sh install
    
    • 安装成功后,执行如下命令,将安装目录内的 conf 目录下的配置文件拷贝到/etc/fdfs/目录下:
    cd conf/
    cp ./* /etc/fdfs/
    
    • 接下来进入/etc/fdfs/目录下配置几个文件中的参数,注意:元数据存储目录要提前创建好(即下面的base_path)!
    • vim tracker.conf,修改其中几个参数值:
    port=22122
    base_path=/opt/fastdfs #这里我就不区分tracker和storage,都将其存在同一目录下
    http.server_port=443 #若不用https来访问,则忽略设置此参数
    
    • vim storage.conf,修改其中几个参数值:
    base_path=/opt/fastdfs #这里我就不区分tracker和storage,都将其存在同一目录下
    store_path0=/opt/fastdfs #存储文件的绝对路径为:$store_path0/data/
    tracker_server=服务器主机外网ip:22122 # 这里只用了1个tracker服务器
    http.server_port=443 #若不用https来访问,则忽略设置此参数
    
    • 分别启动 Tracker 和 Storage 服务:
    /usr/bin/fdfs_trackerd /etc/fdfs/tracker.conf start
    /usr/bin/fdfs_storaged /etc/fdfs/storage.conf start
    
    启动成功
    • 接下来进行Nginx 的安装,分为两个步骤:①安装 Nginx;②在 Storage 下安装 fastdfs-nginx-module
    • ①下载Nginx依赖包:wget http://nginx.org/download/nginx-1.17.0.tar.gz,将nginx-1.17.0.tar.gz压缩包拷贝并解压到/opt/目录下,在编译安装之前,还需要安装两个依赖,即依次执行以下命令,装好之后,默认安装位置在 :/usr/local/nginx/sbin/nginx,有关 Nginx教程笔记:点我即达
    tar -zxvf nginx-1.17.0.tar.gz
    cd nginx-1.17.0
    yum -y install pcre-devel
    yum -y install openssl openssl-devel
    ./configure
    make
    make install
    
    • ②将fastdfs-nginx-module-master.zip拷贝到/usr/local目录下,然后依次执行如下命令:
    cd /usr/local
    unzip fastdfs-nginx-module-master.zip
    mv fastdfs-nginx-module-master fastdfs-nginx-module # 更改文件夹名称
    cp /usr/local/fastdfs-nginx-module/src/mod_fastdfs.conf  /etc/fdfs/ # 将mod_fastdfs.conf配置文件拷贝到 /etc/fdfs/ 目录下
    
    • vim /etc/fdfs/mod_fastdfs.conf,修改其中几个参数值:
    tracker_server=服务器外网ip:22122
    url_have_group_name = true # url是否包含group名,默认要开启
    store_path0=/opt/fastdfs #文件存储目录,默认和前面一样
    
    • 接下来,回到第一步下载的 nginx 安装文件的解压目录/opt/nginx-1.17.0/下,执行如下命令,重新配置编译安装,这里分2个版本:http访问版和https访问版本:
    • http访问版:
    ./configure --add-module=/usr/local/fastdfs-nginx-module/src
    make
    make install
    
    • https访问版,注意:提前备份原来的nginx启动命令,防止配置错误以备还原:
    ./configure --prefix=/usr/local/nginx/ --conf-path=/usr/local/nginx/conf/nginx.conf --with-http_ssl_module --add-module=/usr/local/fastdfs-nginx-module/src
    make
    # 若是从http版本过来的,不需要执行下面这一条安装命令,只需要生存新的nginx启动项即可
    make install 
    # 若是从http版本过来的,还需将新生存的nginx 拷贝到运行目录,否则不执行。
    cp objs/nginx   /usr/local/nginx/sbin/nginx
    
    • 校验 Nginx 配置文件的情况:./nginx -t
    校验成功
    • 安装完成后,修改 Nginx 的配置文件,若是http访问版,则可以省略root /opt/fastdfs;这一行,但若是https访问版,最好加上!最后启动一下Nginx:./nginx
    配置fastdfs文件请求转发 强制将http转发为https 简单配置ssl证书
    • Springboot + fastdfs 实战案例:
    • 添加pom依赖:
    <dependency>
      <groupId>net.oschina.zcx7878</groupId>
      <artifactId>fastdfs-client-java</artifactId>
      <version>1.27.0.0</version>
    </dependency>
    
    • 在项目的 resources 目录下添加 FastDFS 的配置文件fastdfs-client.properties,内容如下:
    fastdfs.connect_timeout_in_seconds=5
    fastdfs.network_timeout_in_seconds=30
    fastdfs.charset=UTF-8
    fastdfs.http_anti_steal_token=false #禁用防盗链,相关配置在 /etc/fdfs/http.conf 中
    fastdfs.http_secret_key=FastDFS1234567890 # 默认和配置文件一样,若开启防盗链,则必须不外露这个密钥,最好设置成长度长且复杂一点
    fastdfs.http_tracker_http_port=80
    fastdfs.tracker_servers=服务器外网ip:22122
    fastdfs.connection_pool.enabled=true
    fastdfs.connection_pool.max_count_per_entry=500
    fastdfs.connection_pool.max_idle_time=3600
    fastdfs.connection_pool.max_wait_time_in_ms=1000
    
    • 添加工具类:FastDFSUtil.java
    import org.csource.common.MyException;
    import org.csource.fastdfs.*;
    import org.springframework.web.multipart.MultipartFile;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.security.NoSuchAlgorithmException;
    import java.time.Instant;
    public class FastDFSUtil {
        private static StorageClient1 client1;
        static {
            try {
                ClientGlobal.initByProperties("fastdfs-client.properties");
                TrackerClient trackerClient = new TrackerClient();
                TrackerServer trackerServer = trackerClient.getConnection();
                client1 = new StorageClient1(trackerServer, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        /**
         * 上传文件
         */
        public static String uploadFile(MultipartFile file) throws IOException, MyException {
            String fileName = file.getOriginalFilename();
            //返回上传到服务器的路径
            return client1.upload_file1(file.getBytes(), fileName.substring(fileName.lastIndexOf(".") + 1), null);
        }
    
        /**
         * 下载文件
         */
        public static byte[] downloadFile(String fileId) throws IOException, MyException {
            return client1.download_file1(fileId);
        }
        //测试
        public static String uploadFile(String localFilePath) throws IOException, MyException {
            return client1.upload_file1(localFilePath, localFilePath.substring(localFilePath.lastIndexOf(".") + 1), null);
        }
        /**
         * 获取访问文件的令牌,有全局异常处理(开启防盗链的情况下)
         */
        public static String getToken(String fileId) throws UnsupportedEncodingException, NoSuchAlgorithmException, MyException {
            int ts = (int) Instant.now().getEpochSecond();
            String subStr = fileId.substring(7); // 注意,这个地址里边不包含 group,千万别搞错了
            String token = ProtoCommon.getToken(subStr, ts, "FastDFS1234567890"); // FastDFS1234567890 是前面配置的参数 fastdfs.http_secret_key 的值
            StringBuilder sb = new StringBuilder();
            String IP = "http(s)://xx.xx.xx.x/"; //服务器外网ip,括号中的 s 表示按照前面自己的配置来决定是http还是https访问
            sb.append(IP);
            sb.append(fileId);
            sb.append("?token=").append(token);
            sb.append("&ts=").append(ts);
            return sb.toString();
        }
    }
    
    • Controller层http接口的编写如下:
    //上传文件
    @PostMapping("/uploadFile")
    @ResponseBody
    public R uploadFile(MultipartFile file) throws IOException, MyException {
        //根据扩展名来设置消息类型:emoji/text/img/file/sys/whiteboard/video/audio
        String filePartName = FastDFSUtil.uploadFile(file);
        String filePath = nginxHost + filePartName; // nginxHost 为服务器域名,注意跟前面设置http还是https访问保持一致
        System.out.println("在服务器的文件名为:" + filePartName);
        return R.ok().data("filePath", filePath);
    }
    //提供文件下载
    @GetMapping("/downloadFile")
    public void downloadFile(@RequestParam("fileId") String fileId,
                             @RequestParam("fileName") String fileName,
                             HttpServletResponse resp) {
        try {
            byte[] bytes = FastDFSUtil.downloadFile(fileId);
            resp.setCharacterEncoding("UTF-8");
            resp.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            ServletOutputStream outputStream = resp.getOutputStream();
            IOUtils.write(bytes, outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    • 通过文件fileId来取得其访问令牌的编写测试:
    @Test
    void testGetFileToken() throws UnsupportedEncodingException, NoSuchAlgorithmException, MyException {
       String fileId = "group1/M00/00/00/wKgxxxAgGBxxxxxsMM090.jpg";
       String fileUrl = FastDFSUtil.getToken(fileId);
       System.out.println(fileUrl);
    }
    

    相关文章

      网友评论

        本文标题:Centos7.x 搭建FastDFS并通过Nginx配置htt

        本文链接:https://www.haomeiwen.com/subject/wxubcltx.html