FastDFS分布式文件系统封装JAVA client工具类

2018-03-21 15:36:53
1407次阅读
0个评论
工具类当中进行连接池的初始化及上传、下载、删除功能的实现并在spring配置文件中配置,生成对应的java bean 方便其它类访问。

FastDfsUtil工具类

实现对连接池初始化、上传、删除功能的实现。


import java.net.SocketTimeoutException;  
import java.util.UUID;  
  
import org.csource.common.NameValuePair;  
import org.csource.fastdfs.StorageClient1;  
import org.csource.fastdfs.StorageServer;  
import org.csource.fastdfs.TrackerServer;  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
  
import com.xxxx.common.AppException;  
import com.xxxx.fastdfs.dto.ResultDto;  
import com.xxxx.fastdfs.exception.ERRORS;  
  
/** 
 *  
 * @ClassName: FastDfsUtil 
 * @Description: fastdfs文件操作工具类 1).初始化连接池; 2).实现文件的上传与下载; 
 *  
 */  
public class FastDfsUtil {  
    private static final Logger LOGGER = LoggerFactory  
            .getLogger(FastDfsUtil.class);  
    /** 连接池 */  
    private ConnectionPool connectionPool = null;  
    /** 连接池默认最小连接数 */  
    private long minPoolSize = 10;  
    /** 连接池默认最大连接数 */  
    private long maxPoolSize = 30;  
    /** 当前创建的连接数 */  
    private volatile long nowPoolSize = 0;  
    /** 默认等待时间(单位:秒) */  
    private long waitTimes = 200;  
  
    /** 
     * 初始化线程池 
     *  
     * @Description: 
     *  
     */  
    public void init() {  
        String logId = UUID.randomUUID().toString();  
        LOGGER.info("[初始化线程池(Init)][" + logId + "][默认参数:minPoolSize="  
                + minPoolSize + ",maxPoolSize=" + maxPoolSize + ",waitTimes="  
                + waitTimes + "]");  
        connectionPool = new ConnectionPool(minPoolSize, maxPoolSize, waitTimes);  
    }  
  
    /** 
     *  
     * @Description: TODO(这里用一句话描述这个方法的作用) 
     * @param groupName 
     *            组名如group0 
     * @param fileBytes 
     *            文件字节数组 
     * @param extName 
     *            文件扩展名:如png 
     * @param linkUrl 
     *            访问地址:http://image.xxx.com 
     * @return 图片上传成功后地址 
     * @throws AppException 
     *  
     */  
    public String upload(String groupName, byte[] fileBytes, String extName,  
            String linkUrl) throws AppException {  
        String logId = UUID.randomUUID().toString();  
        /** 封装文件信息参数 */  
        NameValuePair[] metaList = new NameValuePair[] { new NameValuePair(  
                "fileName", "") };  
        TrackerServer trackerServer = null;  
        try {  
  
            /** 获取fastdfs服务器连接 */  
            trackerServer = connectionPool.checkout(logId);  
            StorageServer storageServer = null;  
            StorageClient1 client1 = new StorageClient1(trackerServer,  
                    storageServer);  
  
            /** 以文件字节的方式上传 */  
            String[] results = client1.upload_file(groupName, fileBytes,  
                    extName, metaList);  
  
            /** 上传完毕及时释放连接 */  
            connectionPool.checkin(trackerServer, logId);  
  
            LOGGER.info("[上传文件(upload)-fastdfs服务器相应结果][" + logId  
                    + "][result:results=" + results + "]");  
  
            ResultDto result = null;  
  
            /** results[0]:组名,results[1]:远程文件名 */  
            if (results != null && results.length == 2) {  
  
                return linkUrl + "/" + results[0] + "/" + results[1];  
            } else {  
                /** 文件系统上传返回结果错误 */  
                throw ERRORS.UPLOAD_RESULT_ERROR.ERROR();  
            }  
        } catch (AppException e) {  
  
            LOGGER.error("[上传文件(upload)][" + logId + "][异常:" + e + "]");  
            throw e;  
  
        } catch (SocketTimeoutException e) {  
            LOGGER.error("[上传文件(upload)][" + logId + "][异常:" + e + "]");  
            throw ERRORS.WAIT_IDLECONNECTION_TIMEOUT.ERROR();  
        } catch (Exception e) {  
  
            LOGGER.error("[上传文件(upload)][" + logId + "][异常:" + e + "]");  
            connectionPool.drop(trackerServer, logId);  
            throw ERRORS.SYS_ERROR.ERROR();  
  
        }  
  
    }  
  
    /** 
     *  
     * @Description: 删除fastdfs服务器中文件 
     * @param group_name 
     *            组名 
     * @param remote_filename 
     *            远程文件名称 
     * @throws AppException 
     *  
     */  
    public void deleteFile(String group_name, String remote_filename)  
            throws AppException {  
  
        String logId = UUID.randomUUID().toString();  
        LOGGER.info("[ 删除文件(deleteFile)][" + logId + "][parms:group_name="  
                + group_name + ",remote_filename=" + remote_filename + "]");  
        TrackerServer trackerServer = null;  
  
        try {  
            /** 获取可用的tracker,并创建存储server */  
            trackerServer = connectionPool.checkout(logId);  
            StorageServer storageServer = null;  
            StorageClient1 client1 = new StorageClient1(trackerServer,  
                    storageServer);  
            /** 删除文件,并释放 trackerServer */  
            int result = client1.delete_file(group_name, remote_filename);  
  
            /** 上传完毕及时释放连接 */  
            connectionPool.checkin(trackerServer, logId);  
  
            LOGGER.info("[ 删除文件(deleteFile)--调用fastdfs客户端返回结果][" + logId  
                    + "][results:result=" + result + "]");  
  
            /** 0:文件删除成功,2:文件不存在 ,其它:文件删除出错 */  
            if (result == 2) {  
  
                throw ERRORS.NOT_EXIST_FILE.ERROR();  
  
            } else if (result != 0) {  
  
                throw ERRORS.DELETE_RESULT_ERROR.ERROR();  
  
            }  
  
        } catch (AppException e) {  
  
            LOGGER.error("[ 删除文件(deleteFile)][" + logId + "][异常:" + e + "]");  
            throw e;  
  
        } catch (SocketTimeoutException e) {  
            LOGGER.error("[ 删除文件(deleteFile)][" + logId + "][异常:" + e + "]");  
            throw ERRORS.WAIT_IDLECONNECTION_TIMEOUT.ERROR();  
        } catch (Exception e) {  
  
            LOGGER.error("[ 删除文件(deleteFile)][" + logId + "][异常:" + e + "]");  
            connectionPool.drop(trackerServer, logId);  
            throw ERRORS.SYS_ERROR.ERROR();  
  
        }  
    }  
  
    public ConnectionPool getConnectionPool() {  
        return connectionPool;  
    }  
  
    public void setConnectionPool(ConnectionPool connectionPool) {  
        this.connectionPool = connectionPool;  
    }  
  
    public long getMinPoolSize() {  
        return minPoolSize;  
    }  
  
    public void setMinPoolSize(long minPoolSize) {  
        this.minPoolSize = minPoolSize;  
    }  
  
    public long getMaxPoolSize() {  
        return maxPoolSize;  
    }  
  
    public void setMaxPoolSize(long maxPoolSize) {  
        this.maxPoolSize = maxPoolSize;  
    }  
  
    public long getNowPoolSize() {  
        return nowPoolSize;  
    }  
  
    public void setNowPoolSize(long nowPoolSize) {  
        this.nowPoolSize = nowPoolSize;  
    }  
  
    public long getWaitTimes() {  
        return waitTimes;  
    }  
  
    public void setWaitTimes(long waitTimes) {  
        this.waitTimes = waitTimes;  
    }  
}
property.properties文件配置


#fastdfs连接池最大连接数  
maxPoolSize=30  
#fastdfs等待时间(单位:秒)  
waitTimes=400  
#fastdfs连接池最小连接数  
minPoolSize=20

spring配置文件


<bean id="propertyConfigurer"  
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="locations">  
            <list>  
                <value>classpath:property.properties</value>  
            </list>  
        </property>  
    </bean>  
    <bean name="connectionPool" class="com.xxxx.fastdfs.pool.FastDfsUtil"  
        init-method="init">  
        <property name="minPoolSize" value="${minPoolSize}" />  
        <property name="maxPoolSize" value="${maxPoolSize}" />  
        <property name="waitTimes" value="${waitTimes}" />  
    </bean>

代码中用到的其它类代码如下:

error枚举类

import com.xxxx.common.AppException;  
import com.xxxx.common.Module;  
  
/** 
 *  
 * @ClassName: ERRORS 
 * @Description: 应用异常枚举类  
 *  
 */  
public enum ERRORS {  
  
    PARAMETER_IS_NULL("21001", "必填参数为空", "必填参数为空"),  
  
    FASTDFS_CONNECTION_FAIL("21002", "连接fastdfs服务器失败", "文件上传异常,请重试"),  
  
    WAIT_IDLECONNECTION_TIMEOUT("21003", "等待空闲连接超时", "连接超时,请重试"),  
  
    NOT_EXIST_GROUP("21004", "文件组不存在", "文件组不存在"),  
  
    UPLOAD_RESULT_ERROR("21005", "fastdfs文件系统上传返回结果错误", "文件上传异常,请重试"),  
  
    NOT_EXIST_PORTURL("21006", "未找到对应的端口和访问地址", "文件上传异常,请重试"),  
  
    SYS_ERROR("21007", "系统错误", "系统错误"),  
  
    FILE_PATH_ERROR("21008", "文件访问地址格式不对","文件访问地址格式不对"),  
  
    DELETE_RESULT_ERROR("21009", "fastdfs文件系统删除文件返回结果错误", "文件删除异常,请重试"),  
  
    NOT_EXIST_FILE("21010", "文件不存在", "文件不存在");  
  
    /** 错误码 */  
    String code;  
  
    /** 错误信息,用于日志输出,便于问题定位 */  
    String message;  
  
    /** 错误提示,用于客户端提示 */  
    String descreption;  
  
    ERRORS(String code, String message) {  
        this.message = message;  
        this.code = code;  
    }  
  
    ERRORS(String code, String message, String descreption) {  
        this.message = message;  
        this.code = code;  
        this.descreption = descreption;  
    }  
  
    public AppException ERROR() {  
        return new AppException(Module.FASTDFS, this.code, this.message,  
                this.descreption);  
    }  
  
    public AppException ERROR(String descreption) {  
        return new AppException(Module.FASTDFS, this.code, this.message,  
                descreption);  
    }  
}

异常类

/** 
 * 系统通用异常 
 * 
 */  
public class AppException extends Exception {  
    private static final long serialVersionUID = -1848618491499044704L;  
  
    private Module module;  
    private String code;  
    private String description;  
  
  
    public AppException(Module module, String code, String message) {  
        super(message);  
        this.module = module;  
        this.code = code;  
    }  
  
    public AppException(Module module, String code, String message, String description) {  
        super(message);  
        this.module = module;  
        this.code = code;  
        this.description = description;  
    }  
  
    /** 
     * 产生异常的模块 
     *  
     * @return 
     */  
    public Module getModule() {  
        return module;  
    }  
  
    /** 
     * 错误码 
     *  
     * @return 
     */  
    public String getCode() {  
        return code;  
    }  
  
    /** 
     * 用户可读描述信息 
     *  
     * @return 
     */  
    public String getDescription() {  
        return description;  
    }  
  
    @Override  
    public String toString() {  
        StringBuilder sb = new StringBuilder();  
        sb.append(getClass().getName());  
        sb.append(": [");  
        sb.append(module);  
        sb.append("] - ");  
        sb.append(code);  
        sb.append(" - ");  
        sb.append(getMessage());  
        if (getDescription() != null) {  
            sb.append(" - ");  
            sb.append(getDescription());  
        }  
        return sb.toString();  
    }  
}
收藏00

登录 后评论。没有帐号? 注册 一个。