CentOS7_2单机环境部署FastDFS文件系统

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_31122833/article/details/101012357

CentOS7_2单机环境部署FastDFS文件系统

一、下载FastDFS所需包(重要,版本亲测有效,切不可更换)

安装Fastdfs文件系统软件.rar 

二、下载完成后,统一将文件放入/usr/local/src目录下

cd /usr/local/src/glibc
rpm -ivh --nodeps --force *.rpm
安装完
cd /usr/local/src/Basic_package
rpm -ivh --nodeps --force *.rpm
安装完
cd /usr/local/src/gcc-etc
rpm -ivh --nodeps --force *.rpm
安装完

三、安装FastDFS环境

vim /etc/hosts

增加如下一行,这是我的IP
192.168.0.222 file.luda.com

如果要本机访问虚拟机,在C:\Windows\System32\drivers\etc\hosts中同样增加一行

   3.1、安装 libfastcommon

解压
cd /usr/local/src/
tar -zxvf libfastcommon-1.0.7.tar
cd libfastcommon-1.0.7

编译、安装
./make.sh
./make.sh install

注:libfastcommon.so 安装到了/usr/lib64/libfastcommon.so,但是FastDFS主程序设置的lib目录是/usr/local/lib,所以需要创建软链接。
ln -s /usr/lib64/libfastcommon.so /usr/local/lib/libfastcommon.so
ln -s /usr/lib64/libfastcommon.so /usr/lib/libfastcommon.so
ln -s /usr/lib64/libfdfsclient.so /usr/local/lib/libfdfsclient.so
ln -s /usr/lib64/libfdfsclient.so /usr/lib/libfdfsclient.so 

   3.2、安装FastDFS

解压
tar -zxvf V5.05.tar.gz
cd fastdfs-5.05

编译、安装
./make.sh
./make.sh install

建立 /usr/bin 到 /usr/local/bin 的软链接。  
ln -s /usr/bin/fdfs_trackerd   /usr/local/bin
ln -s /usr/bin/fdfs_storaged   /usr/local/bin
ln -s /usr/bin/stop.sh         /usr/local/bin
ln -s /usr/bin/restart.sh      /usr/local/bin

  3.3、配置FastDFS跟踪器(Tracker)

进入 /etc/fdfs,复制 FastDFS 跟踪器样例配置文件 tracker.conf.sample,并重命名为 tracker.conf。
cd /etc/fdfs
cp tracker.conf.sample tracker.conf
vim tracker.conf

编辑tracker.conf ,下面的需要修改下,其它的默认即可。
base_path=/luda/fastdfs/tracker
http.server_port=80
创建tracker基础数据目录,即base_path对应的目录
mkdir -p /luda/fastdfs/tracker
查看防火墙状态
systemctl status firewalld.service
关闭防火墙
systemctl stop firewalld.service
移除开机自启
systemctl disable firewalld.service
启动Tracker
初次成功启动,会在 /luda/fdfsdfs/tracker/ (配置的base_path)下创建 data、logs 两个目录。

可以用这种方式启动
/etc/init.d/fdfs_trackerd start

也可以用这种方式启动,前提是上面创建了软链接,后面都用这种方式
service fdfs_trackerd start
查看 FastDFS Tracker 是否已成功启动 ,22122端口正在被监听,则算是Tracker服务安装成功。
netstat -unltp|grep fdfs

关闭Tracker命令:
service fdfs_trackerd stop

设置Tracker开机启动
chkconfig fdfs_trackerd on

 3.4、配置 FastDFS 存储 (Storage)

进入 /etc/fdfs 目录,复制 FastDFS 存储器样例配置文件 storage.conf.sample,并重命名为 storage.conf
cd /etc/fdfs
cp storage.conf.sample storage.conf
vim storage.conf
编辑storage.conf,下面的需要修改,其它的默认即可。
base_path=/luda/fastdfs/storage
store_path0=/luda/fastdfs/file
tracker_server=file.luda.com:22122
http.server_port=80

创建Storage基础数据目录,对应base_path目录
mkdir -p /luda/fastdfs/storage

这是配置的store_path0路径
mkdir -p /luda/fastdfs/file
启动 Storage
启动Storage前确保Tracker是启动的。初次启动成功,会在 /luda/fastdfs/storage 目录下创建 data、 logs 两个目录。

可以用这种方式启动
/etc/init.d/fdfs_storaged start

也可以用这种方式,后面都用这种
service fdfs_storaged start
查看 Storage 是否成功启动,23000 端口正在被监听,就算 Storage 启动成功。
netstat -unltp|grep fdfs

关闭Storage命令:(先别执行)
service fdfs_storaged stop
查看Storage和Tracker是否在通信:
/usr/bin/fdfs_monitor /etc/fdfs/storage.conf

设置 Storage 开机启动
chkconfig fdfs_storaged on

  3.5、文件上传测试

修改 Tracker 服务器中的客户端配置文件 
cd /etc/fdfs
cp client.conf.sample client.conf
vim client.conf
修改如下配置即可,其它默认。
base_path=/luda/fastdfs/client
tracker_server=file.luda.com:22122
mkdir -p /luda/fastdfs/client
上传测试
在linux内部执行如下命令上传 namei.jpeg 图片
/usr/bin/fdfs_upload_file /etc/fdfs/client.conf namei.jpeg

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

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

 四、安装Nginx

上面将文件上传成功了,但我们无法下载。因此安装Nginx作为服务器以支持Http方式访问文件。同时,后面安装FastDFS的Nginx模块也需要Nginx环境。
Nginx只需要安装到StorageServer所在的服务器即可,用于访问文件。我这里由于是单机,TrackerServer和StorageServer在一台服务器上。
1、安装nginx所需环境  
① gcc
② PCRE pcre-devel
③ zlib 安装
④ OpenSSL 安装
已经在第一步装好了
安装Nginx
解压
cd /usr/local/src/
tar -zxvf nginx-1.12.0.tar.gz
cd nginx-1.12.0

使用默认配置
./configure

编译、安装
make
make install

启动nginx
cd /usr/local/nginx/sbin/
./nginx 

设置开机启动
vim /etc/rc.local

添加一行:
/usr/local/nginx/sbin/nginx

设置执行权限
chmod 755 rc.local

查看nginx的版本及模块
/usr/local/nginx/sbin/nginx -V
修改nginx.conf

vim /usr/local/nginx/conf/nginx.conf
添加如下行,将 /group1/M00 映射到 /luda/fastdfs/file/data
location /group1/M00 {
    alias /luda/fastdfs/file/data;
}

重启nginx
/usr/local/nginx/sbin/nginx -s reload
在浏览器访问之前上传的图片、成功。
http://file.luda.com/group1/M00/00/00/wKgz6lnduTeAMdrcAAEoRmXZPp870.jpeg

五、FastDFS 配置 Nginx 模块

fastdfs-nginx-module 模块说明
  FastDFS 通过 Tracker 服务器,将文件放在 Storage 服务器存储, 但是同组存储服务器之间需要进行文件复制, 有同步延迟的问题。
  假设 Tracker 服务器将文件上传到了 192.168.0.222,上传成功后文件 ID已经返回给客户端。
  此时 FastDFS 存储集群机制会将这个文件同步到同组存储 192.168.0.15,在文件还没有复制完成的情况下,客户端如果用这个文件 ID 在 192.168.0.15 上取文件,就会出现文件无法访问的错误。
  而 fastdfs-nginx-module 可以重定向文件链接到源服务器取文件,避免客户端由于复制延迟导致的文件无法访问错误。
fastdfs-nginx-module、解压
cd usr/local/src/
tar -zxvf fastdfs-nginx-module_v1.15.tar.gz

配置Nginx
在nginx中添加模块
先停掉nginx服务
/usr/local/nginx/sbin/nginx -s stop
进入解压包目录
cd /usr/local/src/nginx-1.12.0/

添加模块
./configure --add-module=../fastdfs-nginx-module/src

重新编译、安装
make && make install

如果报错了:
编辑 fastdfs-nginx-module-1.20/src/config 文件  
修改文件内容(去掉路径中的local)

ngx_module_incs="/usr/include/fastdfs /usr/include/fastcommon/"
查看Nginx的模块
/usr/local/nginx/sbin/nginx -V

复制 fastdfs-nginx-module 源码中的配置文件到/etc/fdfs 目录, 并修改
cd /usr/local/src/fastdfs-nginx-module/src
cp mod_fastdfs.conf /etc/fdfs/
修改如下配置,其它默认
connect_timeout=10
tracker_server=file.luda.com:22122
url_have_group_name = true
store_path0=/luda/fastdfs/file
复制 FastDFS 的部分配置文件到/etc/fdfs 目录
cd /usr/local/src/fastdfs-5.05/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;
}
在/luda/fastdfs/file 文件存储目录下创建软连接,将其链接到实际存放数据的目录,这一步可以省略。
ln -s /luda/fastdfs/file/data/ /luda/fastdfs/file/data/M00 
启动nginx
/usr/local/nginx/sbin/nginx
在地址栏访问。
能下载文件就算安装成功。注意和第三点中直接使用nginx路由访问不同的是,这里配置 fastdfs-nginx-module 模块,可以重定向文件链接到源服务器取文件。
http://file.ljzsg.com/group1/M00/00/00/wKgz6lnduTeAMdrcAAEoRmXZPp870.jpeg

六、最终部署结构图(盗的图):可以按照下面的结构搭建环境。

 七、Java对接

一、添加依赖:
<!-- 文件服务系统 -->
<dependency>
    <groupId>com.github.tobato</groupId>
    <artifactId>fastdfs-client</artifactId>
    <version>1.25.2-RELEASE</version>
</dependency>

二、添加配置:
#文件服务器
fdfs.soTimeout=1500
fdfs.connectTimeout= 600
#缩略图生成参数
fdfs.thumbImage.width=150
fdfs.thumbImage.height=150
#TrackerList参数,支持多个
fdfs.trackerList[0]=192.168.0.222:22122
fdfs.configPath=file.luda.com
fdfs.domainPath=file.luda.com
Java代码接口:
    /**
     * 上传文件
     * 无大小限制
     * @param file
     * @return
     */
    public Result<String> uploadFile(MultipartFile file);

    public Result<String> uploadFile(File file) throws IOException;

    /**
     * 上传图片文件(5M限制)
     * @param file
     * @return
     */
    public Result<String> uploadImage(MultipartFile file);

    /**
     * 上传声音文件(5M限制)
     * @param file
     * @return
     */
    public Result<String> uploadVoice(MultipartFile file);

    /**
     * 上传视频文件(10M限制)
     * @param file
     * @return
     */
    public Result<String> uploadVideo(MultipartFile file);

    /**
     * 删除文件
     * @param fileUrl
     */
    public void deleteFile(String fileUrl);

    /**
     * 下载文件至服务器临时文件夹
     * @param fileUrl
     * @return
     */
    public File downloadFileForTemp(String fileUrl);

    /**
     * 下载文件至服务器永久文件夹
     * @param fileUrl
     * @return
     */
    public File downloadFileForForever(String fileUrl);
Java代码接口实现:
    private static Logger logger=LoggerFactory.getLogger(FileUtilServiceImpl.class);

    @Autowired
    private FastFileStorageClient storageClient;

    //ip地址
    @Value("${fdfs.configPath}")
    String configPath;

    //域名地址
    @Value("${fdfs.domainPath}")
    String domainPath;

    @Override
    public Result<String> uploadFile(MultipartFile file) {
        Result result = new Result();
        if (file != null && !file.isEmpty()) {
            try {

                StorePath storePath = storageClient.uploadFile((InputStream)file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);
                String fileUrl=getResAccessUrl(storePath);
                result.setType(FileReturnEnum.UploadEnum.success.value);
                result.setData(fileUrl);
                result.setMessage(FileReturnEnum.UploadEnum.success.name);

            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage(),e);
                result.setType(FileReturnEnum.UploadEnum.fail.value);
                result.setMessage(FileReturnEnum.UploadEnum.fail.name);
            }
        } else {
            result.setType(FileReturnEnum.UploadEnum.lose.value);
            result.setMessage(FileReturnEnum.UploadEnum.lose.name);
        }
        return result;

    }

    /**
     * 上传文件
     * @param file 文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    @Override
    public Result<String> uploadFile(File file) throws IOException {
        Result result = new Result();
        if (file != null) {
            try {

                FileInputStream inputStream = new FileInputStream (file);
                StorePath storePath = storageClient.uploadFile(inputStream,file.length()
                        , FilenameUtils.getExtension(file.getName()),null);
                String fileUrl=getResAccessUrl(storePath);
                result.setType(FileReturnEnum.UploadEnum.success.value);
                result.setData(fileUrl);
                result.setMessage(FileReturnEnum.UploadEnum.success.name);

            } catch (Exception e) {
                //e.printStackTrace();
                logger.error(e.getMessage(),e);
                result.setType(FileReturnEnum.UploadEnum.fail.value);
                result.setMessage(FileReturnEnum.UploadEnum.fail.name);
            }
        } else {
            result.setType(FileReturnEnum.UploadEnum.lose.value);
            result.setMessage(FileReturnEnum.UploadEnum.lose.name);
        }
        return result;
    }

    // 封装文件完整URL地址
    private String getResAccessUrl(StorePath storePath) {
        String fileUrl = domainPath + "/" + storePath.getFullPath();
        return fileUrl;
    }

    @Override
    public Result<String> uploadImage(MultipartFile file){
        Result result = new Result();
        if(file.isEmpty()){
            //空文件
            result.setType(FileReturnEnum.UploadEnum.fail.value);
            result.setMessage("空文件");
        }else if(file.getSize()>0 && file.getSize()<=5*1024*1024){
            result=uploadFile(file);
        }else{
            //图片文件超过规定的大小5M
            result.setType(FileReturnEnum.UploadEnum.fail.value);
            result.setMessage("图片文件超过规定的大小5M");
        }

        return result;
    }

    @Override
    public Result<String> uploadVoice(MultipartFile file){
        Result result = new Result();
        if(file.isEmpty()){
            //空文件
            result.setType(FileReturnEnum.UploadEnum.fail.value);
            result.setMessage("空文件");
        }else if(file.getSize()>0 && file.getSize()<=5*1024*1024){
            result=uploadFile(file);
        }else{
            //音频文件超过规定的大小5M
            result.setType(FileReturnEnum.UploadEnum.fail.value);
            result.setMessage("音频文件超过规定的大小5M");
        }

        return result;
    }

    @Override
    public Result<String> uploadVideo(MultipartFile file){
        Result result = new Result();
        if(file.isEmpty()){
            //空文件
            result.setType(FileReturnEnum.UploadEnum.fail.value);
            result.setMessage("空文件");
        }else if(file.getSize()>0 && file.getSize()<=10*1024*1024){
            result=uploadFile(file);
        }else{
            //视频文件超过规定的大小10M
            result.setType(FileReturnEnum.UploadEnum.fail.value);
            result.setMessage("视频文件超过规定的大小10M");
        }

        return result;
    }


    @Override
    public void deleteFile(String fileUrl){
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            fileUrl = getFastDFSPath(fileUrl);
            storageClient.deleteFile(fileUrl);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 根据文件url获取fastDFS返回的path(组名+文件名)
     * @param fileUrl
     * @return
     */
    public String getFastDFSPath(String fileUrl){
        if(fileUrl.indexOf(domainPath)!=-1){
            fileUrl = fileUrl.replace(domainPath+"/","");
        }else if(fileUrl.indexOf(configPath)!=-1){
            fileUrl = fileUrl.replace(configPath+"/","");
        }
        return fileUrl;
    }

    //@Value("${eaqulFile.tempPath}")
    @Value("D:\\file\\temp\\")
    String tempPath;
    @Override
    public File downloadFileForTemp(String fileUrl){
        return downloadFile(fileUrl,tempPath);
    }

    //@Value("${eaqulFile.foreverPath}")
    @Value("D:\\file\\forever\\")
    String foreverPath;
    @Override
    public File downloadFileForForever(String fileUrl){
        return downloadFile(fileUrl,foreverPath);
    }

    /**
     * 下载文件
     * @param fileUrl 路径地址如:http://file.luda.com/group1/M01/00/01/ooYBAFqzF3qAPcJrAADyr9_6_Js731.jpg
     * @return
     */
    public File downloadFile(String fileUrl,String parentPath) {
        //byte[] b = storageClient.download_file(group, path);
        File file = new File(parentPath+fileUrl.substring(fileUrl.lastIndexOf("/"),fileUrl.length()));
        try {
            //判断文件夹是否存在
            File fileParent = file.getParentFile();
            if(!fileParent.exists()){
                fileParent.mkdirs();//创建文件夹
            }
            // 判断文件是否存在
            if (!file.exists()){
                System.out.println("文件不存在");
                file.createNewFile();    // 不存在,则创建文件
            }

            OutputStream output = new FileOutputStream(file);
            BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);

            String fastDFSPath=getFastDFSPath(fileUrl);
            //String groupName=path.split("/")[0];

            StorePath storePath = StorePath.praseFromUrl(fastDFSPath);
            String groupName=storePath.getGroup();//group1
            String remoteFilename=storePath.getPath();//M01/00/01/ooYBAFqzF3qAPcJrAADyr9_6_Js731.jpg
            //FileInfo fileInfo= storageClient.queryFileInfo(groupName, remoteFilename);//获取文件信息
            byte[] b = storageClient.downloadFile(groupName,remoteFilename, new DownloadCallback<byte[]>() {
                @Override
                public byte[] recv(InputStream ins) throws IOException {
                    byte[] in2b=IOUtils.toByteArray(ins);
                    /*ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
                    byte[] buff = new byte[100000];
                    int rc = 0;
                    while ((rc = ins.read(buff, 0, 100)) > 0) {
                        swapStream.write(buff, 0, rc);
                    }
                    byte[] in2b = swapStream.toByteArray();
                    swapStream.close();*/
                    ins.close();
                    return in2b;
                }
            });
            logger.info(String.valueOf(b.length));
            try{
                if(b != null){
                    bufferedOutput.write(b);
                }
            }catch (Exception e){
                logger.error(e.getMessage(),e);
            } //用户可能取消了下载
            finally {
                if (output != null)
                    try {
                        bufferedOutput.close();
                        output.close();
                    } catch (IOException e) {
                        logger.error(e.getMessage(),e);
                    }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return file;
    }

猜你喜欢

转载自blog.csdn.net/qq_31122833/article/details/101012357