fastdfs-java-client 使用指南

来源:互联网 发布:上海蓝光数据恢复 编辑:程序博客网 时间:2024/05/24 05:29

fastdfs-java-client 使用指南

示例

    package com.github.onion0715.example.fastdfs;    import com.github.onion0715.example.AppConfig;    import org.csource.fastdfs.*;    import org.slf4j.Logger;    import org.slf4j.LoggerFactory;    import org.springframework.beans.factory.InitializingBean;    import org.springframework.beans.factory.annotation.Autowired;    import org.springframework.stereotype.Component;    /**     *     * Created by onion0715 on 2017/7/18.     */    @Component    public class FastDFSClient implements InitializingBean{        private TrackerClient trackerClient;        private TrackerServer trackerServer;        private StorageServer storageServer;        private StorageClient storageClient;        @Autowired        private AppConfig appConfig;        private Logger logger = LoggerFactory.getLogger(FastDFSClient.class);        public void init(){            try{                String configFileName = appConfig.getFastDfsClientConfigFile();                String groupName = appConfig.getFastDfsGroupName();                /**配置文件优先读取本地文件系统路径,找不到再读classpath路径*/                ClientGlobal.init(configFileName);                trackerClient = new TrackerClient();                /**                * 从配置文件中取tracker的ip和端口建立连接,第一个地址连接失败后,会一次迭代后续地址连接,全部无法连接则失败.错误日志不会打印到文件,而是输出到System.error.                */                trackerServer = trackerClient.getConnection();                /**下面两个步骤会建立一个新的TCP连接,可以通过建立多个连接,也就是多个storageClient来实现连接池的功能,加速操作效率*/                storageServer = trackerClient.getStoreStorage(trackerServer,groupName);                storageClient = new StorageClient(trackerServer,storageServer);            }catch (Exception e){                throw new FastDfsClientException("init exception",e);            }        }        @Override        public void afterPropertiesSet() throws Exception {            if(appConfig.isFastDfsClientEnable()){                init();                logger.info("FastDFS client init done");            }        }        public StorageClient getStorageClient(){            return storageClient;        }    }
    tracker_server=10.0.0.1:22122 #可以设置多个    tracker_server=10.0.0.2:22122     connect_timeout=5 #默认值    network_timeout=30 #默认值    charset=UTF-8 #默认值

实现

  • 底层TCP连接使用的是Java Socket,阻塞IO
  • 大量的异常都是抛出到了 System.out/error
  • 使用storageClient操作时如果storeServer连接未建立,会开启连接操作完成后会关闭连接.
  • 如果要提高存储操作效率,可以使用对象池化库common-pool 建立storageClient的连接池
  • 在小文件5M以内的传输时间大约为100-300ms左右
  • 作者提供的客户端没有使用日志,真是个危险的想法

附录

  • fastdfs 源码
  • fastdfs-client-java 源码
  • 安装配置说明