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

来源:互联网 发布:花生壳远程监控软件 编辑:程序博客网 时间:2024/05/19 03:24

工具类当中进行连接池的初始化及上传、下载、删除功能的实现并在spring配置文件中配置,生成对应的java bean 方便其它类访问。


FastDfsUtil工具类


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


[java] view plain copy
  1. import java.net.SocketTimeoutException;  
  2. import java.util.UUID;  
  3.   
  4. import org.csource.common.NameValuePair;  
  5. import org.csource.fastdfs.StorageClient1;  
  6. import org.csource.fastdfs.StorageServer;  
  7. import org.csource.fastdfs.TrackerServer;  
  8. import org.slf4j.Logger;  
  9. import org.slf4j.LoggerFactory;  
  10.   
  11. import com.xxxx.common.AppException;  
  12. import com.xxxx.fastdfs.dto.ResultDto;  
  13. import com.xxxx.fastdfs.exception.ERRORS;  
  14.   
  15. /** 
  16.  *  
  17.  * @ClassName: FastDfsUtil 
  18.  * @Description: fastdfs文件操作工具类 1).初始化连接池; 2).实现文件的上传与下载; 
  19.  * @author mr_smile2014 mr_smile2014@xxxx.com 
  20.  * @date 2015年11月25日 上午10:21:46 
  21.  *  
  22.  */  
  23. public class FastDfsUtil {  
  24.     private static final Logger LOGGER = LoggerFactory  
  25.             .getLogger(FastDfsUtil.class);  
  26.     /** 连接池 */  
  27.     private ConnectionPool connectionPool = null;  
  28.     /** 连接池默认最小连接数 */  
  29.     private long minPoolSize = 10;  
  30.     /** 连接池默认最大连接数 */  
  31.     private long maxPoolSize = 30;  
  32.     /** 当前创建的连接数 */  
  33.     private volatile long nowPoolSize = 0;  
  34.     /** 默认等待时间(单位:秒) */  
  35.     private long waitTimes = 200;  
  36.   
  37.     /** 
  38.      * 初始化线程池 
  39.      *  
  40.      * @Description: 
  41.      *  
  42.      */  
  43.     public void init() {  
  44.         String logId = UUID.randomUUID().toString();  
  45.         LOGGER.info("[初始化线程池(Init)][" + logId + "][默认参数:minPoolSize="  
  46.                 + minPoolSize + ",maxPoolSize=" + maxPoolSize + ",waitTimes="  
  47.                 + waitTimes + "]");  
  48.         connectionPool = new ConnectionPool(minPoolSize, maxPoolSize, waitTimes);  
  49.     }  
  50.   
  51.     /** 
  52.      *  
  53.      * @Description: TODO(这里用一句话描述这个方法的作用) 
  54.      * @param groupName 
  55.      *            组名如group0 
  56.      * @param fileBytes 
  57.      *            文件字节数组 
  58.      * @param extName 
  59.      *            文件扩展名:如png 
  60.      * @param linkUrl 
  61.      *            访问地址:http://image.xxx.com 
  62.      * @return 图片上传成功后地址 
  63.      * @throws AppException 
  64.      *  
  65.      */  
  66.     public String upload(String groupName, byte[] fileBytes, String extName,  
  67.             String linkUrl) throws AppException {  
  68.         String logId = UUID.randomUUID().toString();  
  69.         /** 封装文件信息参数 */  
  70.         NameValuePair[] metaList = new NameValuePair[] { new NameValuePair(  
  71.                 "fileName""") };  
  72.         TrackerServer trackerServer = null;  
  73.         try {  
  74.   
  75.             /** 获取fastdfs服务器连接 */  
  76.             trackerServer = connectionPool.checkout(logId);  
  77.             StorageServer storageServer = null;  
  78.             StorageClient1 client1 = new StorageClient1(trackerServer,  
  79.                     storageServer);  
  80.   
  81.             /** 以文件字节的方式上传 */  
  82.             String[] results = client1.upload_file(groupName, fileBytes,  
  83.                     extName, metaList);  
  84.   
  85.             /** 上传完毕及时释放连接 */  
  86.             connectionPool.checkin(trackerServer, logId);  
  87.   
  88.             LOGGER.info("[上传文件(upload)-fastdfs服务器相应结果][" + logId  
  89.                     + "][result:results=" + results + "]");  
  90.   
  91.             ResultDto result = null;  
  92.   
  93.             /** results[0]:组名,results[1]:远程文件名 */  
  94.             if (results != null && results.length == 2) {  
  95.   
  96.                 return linkUrl + "/" + results[0] + "/" + results[1];  
  97.             } else {  
  98.                 /** 文件系统上传返回结果错误 */  
  99.                 throw ERRORS.UPLOAD_RESULT_ERROR.ERROR();  
  100.             }  
  101.         } catch (AppException e) {  
  102.   
  103.             LOGGER.error("[上传文件(upload)][" + logId + "][异常:" + e + "]");  
  104.             throw e;  
  105.   
  106.         } catch (SocketTimeoutException e) {  
  107.             LOGGER.error("[上传文件(upload)][" + logId + "][异常:" + e + "]");  
  108.             throw ERRORS.WAIT_IDLECONNECTION_TIMEOUT.ERROR();  
  109.         } catch (Exception e) {  
  110.   
  111.             LOGGER.error("[上传文件(upload)][" + logId + "][异常:" + e + "]");  
  112.             connectionPool.drop(trackerServer, logId);  
  113.             throw ERRORS.SYS_ERROR.ERROR();  
  114.   
  115.         }  
  116.   
  117.     }  
  118.   
  119.     /** 
  120.      *  
  121.      * @Description: 删除fastdfs服务器中文件 
  122.      * @param group_name 
  123.      *            组名 
  124.      * @param remote_filename 
  125.      *            远程文件名称 
  126.      * @throws AppException 
  127.      *  
  128.      */  
  129.     public void deleteFile(String group_name, String remote_filename)  
  130.             throws AppException {  
  131.   
  132.         String logId = UUID.randomUUID().toString();  
  133.         LOGGER.info("[ 删除文件(deleteFile)][" + logId + "][parms:group_name="  
  134.                 + group_name + ",remote_filename=" + remote_filename + "]");  
  135.         TrackerServer trackerServer = null;  
  136.   
  137.         try {  
  138.             /** 获取可用的tracker,并创建存储server */  
  139.             trackerServer = connectionPool.checkout(logId);  
  140.             StorageServer storageServer = null;  
  141.             StorageClient1 client1 = new StorageClient1(trackerServer,  
  142.                     storageServer);  
  143.             /** 删除文件,并释放 trackerServer */  
  144.             int result = client1.delete_file(group_name, remote_filename);  
  145.   
  146.             /** 上传完毕及时释放连接 */  
  147.             connectionPool.checkin(trackerServer, logId);  
  148.   
  149.             LOGGER.info("[ 删除文件(deleteFile)--调用fastdfs客户端返回结果][" + logId  
  150.                     + "][results:result=" + result + "]");  
  151.   
  152.             /** 0:文件删除成功,2:文件不存在 ,其它:文件删除出错 */  
  153.             if (result == 2) {  
  154.   
  155.                 throw ERRORS.NOT_EXIST_FILE.ERROR();  
  156.   
  157.             } else if (result != 0) {  
  158.   
  159.                 throw ERRORS.DELETE_RESULT_ERROR.ERROR();  
  160.   
  161.             }  
  162.   
  163.         } catch (AppException e) {  
  164.   
  165.             LOGGER.error("[ 删除文件(deleteFile)][" + logId + "][异常:" + e + "]");  
  166.             throw e;  
  167.   
  168.         } catch (SocketTimeoutException e) {  
  169.             LOGGER.error("[ 删除文件(deleteFile)][" + logId + "][异常:" + e + "]");  
  170.             throw ERRORS.WAIT_IDLECONNECTION_TIMEOUT.ERROR();  
  171.         } catch (Exception e) {  
  172.   
  173.             LOGGER.error("[ 删除文件(deleteFile)][" + logId + "][异常:" + e + "]");  
  174.             connectionPool.drop(trackerServer, logId);  
  175.             throw ERRORS.SYS_ERROR.ERROR();  
  176.   
  177.         }  
  178.     }  
  179.   
  180.     public ConnectionPool getConnectionPool() {  
  181.         return connectionPool;  
  182.     }  
  183.   
  184.     public void setConnectionPool(ConnectionPool connectionPool) {  
  185.         this.connectionPool = connectionPool;  
  186.     }  
  187.   
  188.     public long getMinPoolSize() {  
  189.         return minPoolSize;  
  190.     }  
  191.   
  192.     public void setMinPoolSize(long minPoolSize) {  
  193.         this.minPoolSize = minPoolSize;  
  194.     }  
  195.   
  196.     public long getMaxPoolSize() {  
  197.         return maxPoolSize;  
  198.     }  
  199.   
  200.     public void setMaxPoolSize(long maxPoolSize) {  
  201.         this.maxPoolSize = maxPoolSize;  
  202.     }  
  203.   
  204.     public long getNowPoolSize() {  
  205.         return nowPoolSize;  
  206.     }  
  207.   
  208.     public void setNowPoolSize(long nowPoolSize) {  
  209.         this.nowPoolSize = nowPoolSize;  
  210.     }  
  211.   
  212.     public long getWaitTimes() {  
  213.         return waitTimes;  
  214.     }  
  215.   
  216.     public void setWaitTimes(long waitTimes) {  
  217.         this.waitTimes = waitTimes;  
  218.     }  
  219. }  

property.properties文件配置


[java] view plain copy
  1. #fastdfs连接池最大连接数  
  2. maxPoolSize=30  
  3. #fastdfs等待时间(单位:秒)  
  4. waitTimes=400  
  5. #fastdfs连接池最小连接数  
  6. minPoolSize=20  


spring文件配置


[java] view plain copy
  1. <bean id="propertyConfigurer"  
  2.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  3.         <property name="locations">  
  4.             <list>  
  5.                 <value>classpath:property.properties</value>  
  6.             </list>  
  7.         </property>  
  8.     </bean>  
  9.     <bean name="connectionPool" class="com.xxxx.fastdfs.pool.FastDfsUtil"  
  10.         init-method="init">  
  11.         <property name="minPoolSize" value="${minPoolSize}" />  
  12.         <property name="maxPoolSize" value="${maxPoolSize}" />  
  13.         <property name="waitTimes" value="${waitTimes}" />  
  14.     </bean>  


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


error枚举类

[java] view plain copy
  1. package com.xxxx.fastdfs.exception;  
  2.   
  3. import com.xxxx.common.AppException;  
  4. import com.xxxx.common.Module;  
  5.   
  6. /** 
  7.  *  
  8.  * @ClassName: ERRORS 
  9.  * @Description: 应用异常枚举类 
  10.  * @author mr_smile2014 mr_smile2014@xxxx.com 
  11.  * @date 2015年21月17日 上午10:22:39 
  12.  *  
  13.  */  
  14. public enum ERRORS {  
  15.   
  16.     PARAMETER_IS_NULL("21001""必填参数为空""必填参数为空"),  
  17.   
  18.     FASTDFS_CONNECTION_FAIL("21002""连接fastdfs服务器失败""文件上传异常,请重试"),  
  19.   
  20.     WAIT_IDLECONNECTION_TIMEOUT("21003""等待空闲连接超时""连接超时,请重试"),  
  21.   
  22.     NOT_EXIST_GROUP("21004""文件组不存在""文件组不存在"),  
  23.   
  24.     UPLOAD_RESULT_ERROR("21005""fastdfs文件系统上传返回结果错误""文件上传异常,请重试"),  
  25.   
  26.     NOT_EXIST_PORTURL("21006""未找到对应的端口和访问地址""文件上传异常,请重试"),  
  27.   
  28.     SYS_ERROR("21007""系统错误""系统错误"),  
  29.   
  30.     FILE_PATH_ERROR("21008""文件访问地址格式不对","文件访问地址格式不对"),  
  31.   
  32.     DELETE_RESULT_ERROR("21009""fastdfs文件系统删除文件返回结果错误""文件删除异常,请重试"),  
  33.   
  34.     NOT_EXIST_FILE("21010""文件不存在""文件不存在");  
  35.   
  36.     /** 错误码 */  
  37.     String code;  
  38.   
  39.     /** 错误信息,用于日志输出,便于问题定位 */  
  40.     String message;  
  41.   
  42.     /** 错误提示,用于客户端提示 */  
  43.     String descreption;  
  44.   
  45.     ERRORS(String code, String message) {  
  46.         this.message = message;  
  47.         this.code = code;  
  48.     }  
  49.   
  50.     ERRORS(String code, String message, String descreption) {  
  51.         this.message = message;  
  52.         this.code = code;  
  53.         this.descreption = descreption;  
  54.     }  
  55.   
  56.     public AppException ERROR() {  
  57.         return new AppException(Module.FASTDFS, this.code, this.message,  
  58.                 this.descreption);  
  59.     }  
  60.   
  61.     public AppException ERROR(String descreption) {  
  62.         return new AppException(Module.FASTDFS, this.code, this.message,  
  63.                 descreption);  
  64.     }  
  65. }  

异常类


[java] view plain copy
  1. package com.xxxx.common;  
  2.   
  3. /** 
  4.  * 系统通用异常 
  5.  * @author mr_smile2014 mr_smile2014@xxxx.com 
  6.  * 
  7.  */  
  8. public class AppException extends Exception {  
  9.     private static final long serialVersionUID = -1848618491499044704L;  
  10.   
  11.     private Module module;  
  12.     private String code;  
  13.     private String description;  
  14.   
  15.   
  16.     public AppException(Module module, String code, String message) {  
  17.         super(message);  
  18.         this.module = module;  
  19.         this.code = code;  
  20.     }  
  21.   
  22.     public AppException(Module module, String code, String message, String description) {  
  23.         super(message);  
  24.         this.module = module;  
  25.         this.code = code;  
  26.         this.description = description;  
  27.     }  
  28.   
  29.     /** 
  30.      * 产生异常的模块 
  31.      *  
  32.      * @return 
  33.      */  
  34.     public Module getModule() {  
  35.         return module;  
  36.     }  
  37.   
  38.     /** 
  39.      * 错误码 
  40.      *  
  41.      * @return 
  42.      */  
  43.     public String getCode() {  
  44.         return code;  
  45.     }  
  46.   
  47.     /** 
  48.      * 用户可读描述信息 
  49.      *  
  50.      * @return 
  51.      */  
  52.     public String getDescription() {  
  53.         return description;  
  54.     }  
  55.   
  56.     @Override  
  57.     public String toString() {  
  58.         StringBuilder sb = new StringBuilder();  
  59.         sb.append(getClass().getName());  
  60.         sb.append(": [");  
  61.         sb.append(module);  
  62.         sb.append("] - ");  
  63.         sb.append(code);  
  64.         sb.append(" - ");  
  65.         sb.append(getMessage());  
  66.         if (getDescription() != null) {  
  67.             sb.append(" - ");  
  68.             sb.append(getDescription());  
  69.         }  
  70.         return sb.toString();  
  71.     }  
  72. }  

注:连接池ConnectionPool类使用的是上一篇文章的类,如果要使用直接去拷贝。
原创粉丝点击