文章首发于:clawhub.club
简介
分布式文件系统FastDFS非常适合中小型项目,比如说作为图片服务器。
happyfish100大神的github:fastdfs,fastdfs-client-java。
简单的对客户端进行了连接池的封装,方便使用。
- 系统启动,池子管理连接
- 心跳确认连接是否可靠
- 构造器模式创建连接池
- 回调方式使用客户端
核心代码
初始化连接池
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
public FastDFSConnPool build() { idleConnectionPool = new LinkedBlockingQueue<>(maxPoolSize); try { ClientGlobal.init(confFileName); } catch (IOException | MyException e) { throw new RuntimeException("init client global exception.", e); } TrackerServer trackerServer; for (int i = 0; i < minPoolSize; i++) { trackerServer = createTrackerServer(); if (trackerServer != null) { idleConnectionPool.offer(trackerServer); } } new HeartBeat(this).beat();
return this; }
|
客户端执行请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
public <T> T processFdfs(CallBack<T> invoke) { TrackerServer trackerServer = null; T t; try { trackerServer = fastDFSConnPool.checkOut(); StorageClient1 storageClient = new StorageClient1(trackerServer, null); t = invoke.invoke(storageClient); fastDFSConnPool.checkIn(trackerServer); return t; } catch (Exception e) { fastDFSConnPool.drop(trackerServer); throw new RuntimeException(e); } }
|
心跳
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
private class HeartBeatTask implements Runnable {
@Override public void run() { LinkedBlockingQueue<TrackerServer> idleConnectionPool = fastDFSConnPool.getIdleConnectionPool(); TrackerServer ts = null; for (int i = 0; i < idleConnectionPool.size(); i++) { try { ts = idleConnectionPool.poll(fastDFSConnPool.getWaitTimes(), TimeUnit.SECONDS); if (ts != null) { ProtoCommon.activeTest(ts.getSocket()); idleConnectionPool.add(ts); } else { break; } } catch (Exception e) { logger.error("heart beat conn have dead, and reconnect.", e); fastDFSConnPool.drop(ts); } }
} }
|
使用方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| FastDFSConnPool fastDFSConnPool = new FastDFSConnPool() .confFileName("./config/fdfs_client.conf") .maxPoolSize(8) .minPoolSize(1) .reConnNum(2) .waitTimes(2).build();
FastDFSClient client = new FastDFSClient(fastDFSConnPool); String parts = client.processFdfs(storageClient -> storageClient.upload_file1("fileName", "extName", new NameValuePair[0])); byte[] bytes = client.processFdfs(storageClient -> storageClient.download_file1("fileId")); int result = client.processFdfs(storageClient -> storageClient.delete_file1("fileId")); FileInfo fileInfo = client.processFdfs(storageClient -> storageClient.get_file_info("groupName", "remoteFileName"));
|
github地址