使用FastDfs作文件服务器

简介

FastDfs是一款优秀的分布式开源文件存储系统,以下就此系统在java项目中的应用做简单介绍。

FastDfs在CentOS7系统中的部署

MrCao杰罗尔德的博客中关于FastDfs的部署做了非常详细的介绍,大家可以参考。

Java项目中的应用

pom.xml中添加依赖

<dependency>
    <groupId>org.csource</groupId>
    <artifactId>fastdfs-client-java</artifactId>
    <version>1.27-SNAPSHOT</version>
</dependency>

resources目录下添加配置文件fdfs_client.conf

connect_timeout = 2
network_timeout = 30
charset = UTF-8
http.tracker_http_port = 9999
http.anti_steal_token = no
http.secret_key = FastDFS1234567890

tracker_server = 120.0.0.1:22122

封装FastDfs文件类FastDfsFile.java

import java.io.Serializable;
import lombok.Data;
/**
 * FastDfs文件封装
 * @author: Iffie
 * @date: 2018年11月21日
 */
@Data
public class FastDfsFile implements Serializable{
	
	private static final long serialVersionUID = 1888532385762169306L;

	private String name;
	
    private byte[] content;
    
    private String ext;
    
    private String md5;
    
    private String author;

	public FastDfsFile(String name, byte[] content, String ext) {
		super();
		this.name = name;
		this.content = content;
		this.ext = ext;
	}

	public FastDfsFile() {
		super();
	}
    
	
}

封装FastDfs操作工具类FastDfsClient.java

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.FileInfo;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;

import lombok.extern.slf4j.Slf4j;

/**
 * FastDfs工具类
 * @author: Iffie
 * @date: 2018年11月21日
 */
@Slf4j
public class FastDfsClient {
	
	private static TrackerClient trackerClient;
    
    private static TrackerServer trackerServer;
    
    private static StorageServer storageServer;
    
    private static StorageClient storageClient;
    
    static {
        try {
            String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();;
            ClientGlobal.init(filePath);
            trackerClient = new TrackerClient();
            trackerServer = trackerClient.getConnection();
            storageServer = trackerClient.getStoreStorage(trackerServer);
        } catch (Exception e) {
            log.error("FastDfsClient Init Fail!",e);
        }
    }
    
    /**
     * 上传
     */
    public static String[] upload(FastDfsFile file) throws Exception {
    	
        log.info("上传文件开始,文件名:{}",file.getName());

        NameValuePair[] metaList = new NameValuePair[1];
        metaList[0] = new NameValuePair("author", file.getAuthor());

        long startTime = System.currentTimeMillis();
        String[] uploadResults = null;
        	storageClient = new StorageClient(trackerServer, storageServer);
            uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), metaList);
        log.info("上传文件耗时:{}毫秒",(System.currentTimeMillis() - startTime));
        if(uploadResults != null) {
        	String groupName = uploadResults[0];
        	String remoteFileName = uploadResults[1];
        	log.info("上传文件成功,groupName:{},remoteFileName:{}",groupName,remoteFileName);
        	return uploadResults;
        }
    	log.error("上传文件失败,错误码:{}",storageClient.getErrorCode());
    	throw new Exception("上传文件失败");
    }
    
    /**
     * 根据groupName和文件名获取文件信息
     */
    public static FileInfo getFile(String groupName, String remoteFileName) {
        try {
            storageClient = new StorageClient(trackerServer, storageServer);
            return storageClient.get_file_info(groupName, remoteFileName);
        }catch (Exception e) {
        	log.error("获取文件信息异常", e);
        }
        return null;
    }
    
    /**
     * 下载
     */
    public static InputStream downFile(String groupName, String remoteFileName) {
        try {
            storageClient = new StorageClient(trackerServer, storageServer);
            byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
            InputStream ins = new ByteArrayInputStream(fileByte);
            return ins;
        }catch (Exception e) {
        	log.error("下载文件异常", e);
        }
        return null;
    }
    
    /**
     * 删除
     */
    public static void deleteFile(String groupName, String remoteFileName)
            throws Exception {
        storageClient = new StorageClient(trackerServer, storageServer);
        int i = storageClient.delete_file(groupName, remoteFileName);
        log.info("删除文件成功" + i);
    }
    
    /**
     * MultipartFile上传
     */
    public static String saveFile(MultipartFile multipartFile) throws Exception {
        String[] fileAbsolutePath={};
        String fileName=multipartFile.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        byte[] fileBuff = null;
        InputStream inputStream=multipartFile.getInputStream();
        if(inputStream!=null){
            int len1 = inputStream.available();
            fileBuff = new byte[len1];
            inputStream.read(fileBuff);
        }
        inputStream.close();
        FastDfsFile file = new FastDfsFile(fileName, fileBuff, ext);
        fileAbsolutePath = FastDfsClient.upload(file);
        if(fileAbsolutePath!=null) {
        	return fileAbsolutePath[0]+ "/"+fileAbsolutePath[1];
        }
        log.error("上传失败");
        throw new Exception("上传失败");
    }
}

猜你喜欢

转载自blog.csdn.net/Iffie_01/article/details/84335810
今日推荐