fastdfsjavaapi连接池.docx
- 文档编号:23383492
- 上传时间:2023-05-16
- 格式:DOCX
- 页数:13
- 大小:33.01KB
fastdfsjavaapi连接池.docx
《fastdfsjavaapi连接池.docx》由会员分享,可在线阅读,更多相关《fastdfsjavaapi连接池.docx(13页珍藏版)》请在冰豆网上搜索。
fastdfsjavaapi连接池
Fastdfs-javaapi-连接池
1简绍
大家都知道fastdfs分为trackerserver和storageserver,trackerserver是跟踪服务器,主要做调度工作,在访问上起负载均衡的作用。
storageserver是存储服务器,主要负责文件的存储。
我们使用javaapi在分布式文件系统的文件去上传、修改、删除等操作时,有以下几步:
1)申请与trackerserver的连接
TrackerClienttrackerClient=newTrackerClient();
TrackerServertrackerServer=trackerClient.getConnection();
2)通过trackerServer得到与storageserver的连接的客户端
StorageServerss=tc.getStoreStorage(ts);
StorageClient1client1=newStorageClient1(trackerServer,ss);
3)上传文件
client1.upload_file1(fileBuff,fileExtName,null);
4)关闭连接
ss.close();
trackerServer.close();
最终可以完成我们想要的操作,但是这两次创建的连接都是tcp/ip连接,如果每次创建完连接我们都再关闭连接。
这个过程是很耗时的。
通过api申请的连接并不支持高发发(即一个storage连接只能上传一个文件),我们必须保证同一时刻一个连接上传一个文件。
由于我们用fastdfs做文件服务器,通过web的管理平台将文件上传至分布式文件系统中,每次申请完连接再关闭连接,对我们来说会延长上传文件的时间,而且上传文件高并发下,申请的连接可能突然增至几百个,这样我们的服务器的性能损耗太大了。
2javaapi源代码分析
通过查看fastdfsjavaapi的源代码了解到。
通过trackerServer和storageServer得到的newStorageClient1(trackerServer,storageServer);client对象,在操作文件时,会自动检查trackerServer和storageServer是否为空,如果为空,程序会自动为任一server创建连接,待操作完成后,将创建的连接关闭。
如果storageServer为null,则程序自动创建trackerServer,根据trackerServer得到storageServer,并返回storageServer,在返回storageServer之前会关闭trackerServer。
通过storageServer上传完文件之后,关闭storageServer.
如果都不空null,则api中不会关闭连接。
3结合实际。
由于我们搭建的文件系统架构是,一个tracker和三个storage.
从这个图形可以看出,我们的tracker连接是没有必要改变的,申请一次就可以,(直接点)故我们可以为tracker创建连接池。
连接池代码如下ConnectionPool:
importjava.io.IOException;
import.InetSocketAddress;
importjava.util.concurrent.ArrayBlockingQueue;
importjava.util.concurrent.ConcurrentHashMap;
importjava.util.concurrent.TimeUnit;
importorg.csource.fastdfs.ClientGlobal;
importorg.csource.fastdfs.StorageClient1;
importorg.csource.fastdfs.StorageServer;
importorg.csource.fastdfs.TrackerClient;
importorg.csource.fastdfs.TrackerGroup;
importorg.csource.fastdfs.TrackerServer;
publicclassConnectionPool{
//thelimitofconnectioninstance
privateintsize=5;
//busyconnectioninstances
privateConcurrentHashMap
//idleconnectioninstances
privateArrayBlockingQueue
privatefinalstaticStringtgStr="192.168.4.117";
privatefinalstaticintport=22122;
privateObjectobj=newObject();
//classmethod
//singleton
privateConnectionPool(){
busyConnectionPool=newConcurrentHashMap
idleConnectionPool=newArrayBlockingQueue
init(size);
};
privatestaticConnectionPoolinstance=newConnectionPool();
//gettheconnectionpoolinstance
publicstaticConnectionPoolgetPoolInstance(){
returninstance;
}
//classmethod
//inittheconnectionpool
privatevoidinit(intsize){
initClientGlobal();
TrackerServertrackerServer=null;
try{
TrackerClienttrackerClient=newTrackerClient();
//Onlytracker
trackerServer=trackerClient.getConnection();
for(inti=0;i StorageServerstorageServer=null; StorageClient1client1=newStorageClient1(trackerServer, storageServer); idleConnectionPool.add(client1); } }catch(IOExceptione){ e.printStackTrace(); }finally{ if(trackerServer! =null){ try{ trackerServer.close(); }catch(IOExceptione){ e.printStackTrace(); } } } } //1.poponeconnectionfromtheidleConnectionPool, //2.pushtheconnectionintobusyConnectionPool; //3.returntheconnection //4.ifnoidleconnection,dowaitforwait_timeseconds,andcheckagain publicStorageClient1checkout(intwaitTimes)throwsInterruptedException{ StorageClient1client1=idleConnectionPool.poll(waitTimes, TimeUnit.SECONDS); busyConnectionPool.put(client1,obj); returnclient1; } //1.poptheconnectionfrombusyConnectionPool; //2.pushtheconnectionintoidleConnectionPool; //3.donessarycleanupworks. publicvoidcheckin(StorageClient1client1){ if(busyConnectionPool.remove(client1)! =null){ idleConnectionPool.add(client1); } } //soiftheconnectionwasbrokenduetosomeerros(like //: socketinitfailure,networkbrokenetc),dropthisconnection //fromthebusyConnectionPool,andinitonenewconnection. publicvoiddrop(StorageClient1client1){ if(busyConnectionPool.remove(client1)! =null){ TrackerServertrackerServer=null; try{ TrackerClienttrackerClient=newTrackerClient(); //TODO此处有内存泄露,因为trackerServer没有关闭连接 trackerServer=trackerClient.getConnection(); StorageServerstorageServer=null; StorageClient1newClient1=newStorageClient1(trackerServer,storageServer); idleConnectionPool.add(newClient1); }catch(IOExceptione){ e.printStackTrace(); }finally{ if(trackerServer! =null){ try{ trackerServer.close(); }catch(IOExceptione){ e.printStackTrace(); } } } } } privatevoidinitClientGlobal(){ InetSocketAddress[]trackerServers=newInetSocketAddress[1]; trackerServers[0]=newInetSocketAddress(tgStr,port); ClientGlobal.setG_tracker_group(newTrackerGroup(trackerServers)); //连接超时的时限,单位为毫秒 ClientGlobal.setG_connect_timeout(2000); //网络超时的时限,单位为毫秒 ClientGlobal.setG_network_timeout(30000); ClientGlobal.setG_anti_steal_token(false); //字符集 ClientGlobal.setG_charset("UTF-8"); ClientGlobal.setG_secret_key(null); } } 上传文件类接口: ImageServer importjava.io.File; importjava.io.IOException; /** *图片文件上传 *@authorzhanghua * */ publicinterfaceImageServer{ /** *上传文件 *@paramfile文件 *@return文件存储路径 *@throwsIOException *@throwsException */ publicStringuploadFile(Filefile)throwsIOException,Exception; /** *上传文件 *@paramfile文件 *@paramname文件名称 *@return文件存储路径 *@throwsIOException *@throwsException */ publicStringuploadFile(Filefile,Stringname)throwsIOException,Exception; /** *上传文件 *@paramfileBuff二进制数组 *@paramname *@return */ publicStringuploadFile(byte[]fileBuff,Stringname)throwsIOException,Exception; } 上传文件实现: ImageServerImpl importjava.io.File; importjava.io.FileInputStream; importjava.io.FileNotFoundException; importjava.io.IOException; import.InetSocketAddress; importorg.csource.fastdfs.ClientGlobal; importorg.csource.fastdfs.StorageClient1; importorg.csource.fastdfs.TrackerGroup; importcom.imageserver.pool.ConnectionPool; publicclassImageServerImplimplementsImageServer{ privatefinalstaticStringtgStr="192.168.4.117"; privatefinalstaticintport=22122; publicImageServerImpl(){ init(); } publicStringuploadFile(Filefile)throwsIOException,Exception{ returnuploadFile(file,file.getName()); } publicStringuploadFile(Filefile,Stringname)throwsIOException, Exception{ byte[]fileBuff=getFileBuffer(file); StringfileExtName=getFileExtName(name); returnsend(fileBuff,fileExtName); } publicStringuploadFile(byte[]fileBuff,Stringname)throwsIOException, Exception{ StringfileExtName=getFileExtName(name); returnsend(fileBuff,fileExtName); } privateStringsend(byte[]fileBuff,StringfileExtName) throwsIOException,Exception{ StringupPath=null; StorageClient1client1=null; try{ client1=ConnectionPool.getPoolInstance().checkout(10); upPath=client1.upload_file1(fileBuff,fileExtName,null); ConnectionPool.getPoolInstance().checkin(client1); }catch(InterruptedExceptione){ //确实没有空闲连接,并不需要删除与fastdfs连接 throwe; }catch(Exceptione){ //发生io异常等其它异常,默认删除这次连接重新申请 ConnectionPool.getPoolInstance().drop(client1); e.printStackTrace(); throwe; } XX文库-让每个人平等地提升自我returnupPath; } privateStringgetFileExtName(Stringname){ StringextName=null; if(name! =null&&name.contains(".")){ extName=name.substring(name.lastIndexOf(".")+1); } returnextName; } privatebyte[]getFileBuffer(Filefile){ byte[]fileByte=null; try{ FileInputStreamfis=newFileInputStream(file); fileByte=newbyte[fis.available()]; fis.read(fileByte); }catch(FileNotFoundExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); } returnfileByte; } privatevoidinit(){ InetSocketAddress[]trackerServers=newInetSocketAddress[1]; trackerServers[0]=newInetSocketAddress(tgStr,port); ClientGlobal.setG_tracker_group(newTrackerGroup(trackerServers)); //连接超时的时限,单位为毫秒 ClientGlobal.setG_connect_timeout(2000); //网络超时的时限,单位为毫秒 ClientGlobal.setG_network_timeout(30000); ClientGlobal.setG_anti_steal_token(false); //字符集 ClientGlobal.setG_charset("UTF-8"); ClientGlobal.setG_secret_key(null); } } 上传文件测试类: ImageServerTest importjava.io.File; importjava.io.IOException; importjava.util.concurrent.atomic.AtomicInteger; publicclassImageServerTest{ ImageServers=newImageServerImpl(); AtomicIntegercount=newAtomicInteger(); staticlongstime=0; publicstaticvoidmain(String[]args){ stime=System.currentTimeMillis(); newImageServerTest().mutiUP(); } publicvoidstatTime(){ if(count.getAndIncrement()==9){ System.out.println("用时: "+(System.currentTimeMillis()-stime)); } } publicvoidmutiUP(){ for(inti=0;i<1;i++){ newThread(){ @Override publicvoidrun(){ try{ for(intj=0;j<10;j++){ Stringp=s.uploadFile(newFile("F: \\pic\\1.jpg")); System.out.println(p); } statTime(); }catch(IOExceptione){ e.printStackTrace(); }catch(Exceptione){ e.printStackTrace(); } } }.start(); } } }
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- fastdfsjavaapi 连接