NIO 实现的一个存储数据,和取数据的文件存储demo:
需求:工作中遇到大批量可用性任务(主要监测网站的http响应时间,dns响应时间,ping的时间,任务频率30s一次),界面需要按照时间显示各个数据趋势图,由于数据频繁,对数据库压力较大,而且历史数据对于其他功能意义不大,故将采用nio做了文件存储。下面demo展示(实际项目复杂的多):
存储数据:
private static void appendData(long timestamp,int http,int dns,int ping) throws Exception{ RandomAccessFile file = new RandomAccessFile("d:/random.txt","rw"); FileChannel fileChannel = file.getChannel(); long totalSize = fileChannel.size(); int recordSize = 8 + 4 + 4 + 4 ; ByteBuffer byteBuffer = ByteBuffer.allocate(recordSize); //假设有4个参数,时间:long,http:int , dns: int ,ping:int 8+4+4+4 = 占20个字节 byteBuffer.clear(); byteBuffer.putLong(timestamp); byteBuffer.putInt(http); byteBuffer.putInt(dns); byteBuffer.putInt(ping); byteBuffer.flip(); fileChannel.write(byteBuffer,totalSize); fileChannel.force(false); file.close(); }
获取数据:
private static void readData(long startTime) throws Exception{ RandomAccessFile file = new RandomAccessFile("d:/random.txt","rw"); FileChannel fileChannel = file.getChannel(); long totalSize = fileChannel.size(); int recordSize = 8 + 4 + 4 + 4 ; int recordNum = (int)totalSize/recordSize; ByteBuffer byteBuffer = ByteBuffer.allocate(recordSize); for(int i = 0; i< recordNum;i++){ byteBuffer.clear(); fileChannel.read(byteBuffer,i * recordSize); byteBuffer.flip(); long timeStamp = byteBuffer.getLong(); if(timeStamp > startTime){ int http = byteBuffer.getInt(); int dns = byteBuffer.getInt(); int ping = byteBuffer.getInt(); System.out.println("http:"+http+" dns:"+dns+" ping:"+ping); } } file.close(); }