package cn.kgc.kb08.es.log; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.text.MessageFormat; import java.util.Random; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class LogService { private ExecutorService es = Executors.newFixedThreadPool(50); private Random rand = new Random(); // userId // eventType private String[] eventType = {"visit","btn_search", "btn_page","btn_add_cart", "btn_make_order","btn_pay"}; // eventMonth // browser private String[] browser = {"chrome","firefox","360","IE","猎豹"}; // clickCount // timeZone private String[] timeZone = {"开罗","伦敦","莫斯科","新德里","北京","悉尼","温哥华"}; private String path; public LogService() { } public LogService(String path) { this.path = path; } private String makeMst(){ Object[] parts = { // 1-100000的随机数 String.valueOf(1+rand.nextInt(10000)), eventType[rand.nextInt(eventType.length)], MessageFormat.format("{0}-{1}", String.valueOf(2010+rand.nextInt(11)), 1+rand.nextInt(12)), browser[rand.nextInt(browser.length)], 1+rand.nextInt(100), timeZone[rand.nextInt(timeZone.length)] }; return MessageFormat.format("{0};{1};{2};{3};{4};{5};",parts); } public static void main (String[] args){ System.out.println(new LogService().makeMst()); } private class RandFileLog implements Runnable{ @Override public void run() { String msg = makeMst(); synchronized (RandomAccessFile.class){ RandomAccessFile raf = null; try { raf = new RandomAccessFile(path,"rw"); raf.seek(raf.length()); // windows系统中换行需要 都用 // raf.writeBytes(msg+" "); //linux下只能用于纯英语 raf.write((msg+" ").getBytes()); //Linux下可以用中文 } catch (Exception e) { e.printStackTrace(); }finally { if(null != raf){ try { raf.close(); } catch (IOException e) { e.printStackTrace(); } } } } } } public void log(int count){ if(count <= 0){ return; } for (int i=0;i<count;i++){ es.submit((Runnable)new RandFileLog()); } } }