Domino毫秒級查詢利器Elasticsearch(二)

     Domino同步到Elasticsearch由於是單線程,時間使用多,能否在原來的基礎上進行優化?是的,由於使用java,可以支持多線程,使用多線程來一次性同步測試一下?
     Domino使用多線程查詢數據庫在以前文章有介紹過了,以下幾張圖片簡要介紹:

已經比沒有使用多線程少500秒的時間,大大壓縮同步時間。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.alibaba.fastjson.JSONObject;

import lotus.domino.*;

public class JavaAgent extends AgentBase {

    public void NotesMain() {

      try {
          Session session = getSession();
          AgentContext agentContext = session.getAgentContext();

        //(Your code goes here)
        Date d1 = new Date();          
        Database db = session.getCurrentDatabase();
        View view =db.getView("AllNames");
        ViewEntryCollection vc=view.getAllEntries();
  
		System.out.println(vc.getCount());
		int setp=1000;
		int taskSize =(int) Math.ceil(vc.getCount()/setp);
			
        // 創建一個線程池  
        ExecutorService pool = Executors.newFixedThreadPool(taskSize>5?5:taskSize);  
        // 創建多個有返回值的任務  
        List<Future> list = new ArrayList<Future>();  
        for (int i = 0; i < taskSize; i++) {  
         Callable c = new MyCallable((i)*setp+1,(i+1)*setp);  
         // 執行任務並獲取Future對象  
         Future f = pool.submit(c);  
         // System.out.println(">>>" + f.get().toString());  
         list.add(f);  
        }  
        // 關閉線程池  
        pool.shutdown();  
       
        // 獲取所有併發任務的運行結果  
        for (Future f : list) {  
         // 從Future對象上獲取任務的返回值,並輸出到控制檯  
         System.out.println(">>>" + f.get().toString());  
        }  

	    Date d2 = new Date();
		System.out.println(d2.getTime() - d1.getTime());
		System.out.println("****** END ********");	
		
      } catch(Exception e) {
          e.printStackTrace();
       }
   }
    
    
    
}

class MyCallable implements Callable<Object> { 
	private int start;  
	private int end; 
	//可以通過更改這MyCallable函數,從外傳遞參數進來,如unid等
	MyCallable(int start,int end) {  
	   this.start = start;
	   this.end = end;
	}  
	  
	public Object call() throws Exception {  
	   System.out.println(">>>" + start + "任務啓動");  
	   Date dateTmp1 = new Date();  
	   //Thread.sleep(1000);  
	   ViewEntry tmpentry=null;
	   try
	      {
			//創建NotesThread對象
		    NotesThread.sinitThread(); 
	        Session session = NotesFactory.createSession();
	 	    Database db = session.getCurrentDatabase();
	 	    View view =db.getView("AllNames");
	        ViewEntryCollection vc=view.getAllEntries();
	 	    ViewEntry entry=vc.getNthEntry(start);
	 	    int i=start;
	 	    System.out.println(">>>start" + start+">>>end" + end );	 	    
	 	    while (entry != null && i<=end) {
		    	i++;		 
		    	String temp="{\"Name\":\""+entry.getColumnValues().elementAt(0).toString()
		    			+"\",\"EMail\":\""+entry.getColumnValues().elementAt(1).toString()+"\"}";
		    	temp=HttpSendSoapPost("PUT","http://localhost:9200/xpages/ext/"+entry.getUniversalID(),temp);
		    	System.out.println(i);
		    	
		        tmpentry = vc.getNextEntry();
		        entry.recycle();
		        entry = tmpentry;
		      }	 	    
	      }		
	    catch (Exception e)
	      {
	        e.printStackTrace();
	      }
		finally
	      {
			//要注意回收
	        NotesThread.stermThread();
	      }
		
	   Date dateTmp2 = new Date();  
	   long time = dateTmp2.getTime() - dateTmp1.getTime();  
	   System.out.println(">>>" + start + "任務終止");  
	   return start + "任務返回運行結果,當前任務時間【" + time + "毫秒】";  
	}
	
	public static String HttpSendSoapPost(String Method,String strurl,String xml){
		HttpURLConnection connection = null;
		InputStream is = null;
		BufferedReader br = null;
		String result = null;// 返回結果字符串
		OutputStream out = null;
		//Date d1 = new Date();
		try {
		
			// 創建遠程url連接對象
			URL url = new URL(strurl);
			// 通過遠程url連接對象打開一個連接,強轉成httpURLConnection類
			
			connection = (HttpURLConnection) url.openConnection();
			// 設置連接方式:GET,POST
			if(Method.equals("")){
				connection.setRequestMethod("POST");
			}else{
				connection.setRequestMethod(Method);
			}
			

			connection.setDoInput(true);
			connection.setDoOutput(true);
			
			connection.setRequestProperty("Content-Type", "application/json");
			//這裏必須要寫,否則出錯
			//connection.setRequestProperty("SOAPAction", "");			
						
			// 設置連接主機服務器的超時時間:15000毫秒
			connection.setConnectTimeout(15000);
			// 設置讀取遠程返回的數據時間:60000毫秒
			connection.setReadTimeout(60000);

			// 發送請求
			connection.connect();
			out = connection.getOutputStream(); // 獲取輸出流對象
			connection.getOutputStream().write(xml.getBytes("UTF-8")); // 將要提交服務器的SOAP請求字符流寫入輸出流
			
			out.flush();
			out.close();

			//System.out.println(connection.getResponseCode());

			// 通過connection連接,獲取輸入流
			if (connection.getResponseCode() == 200 || connection.getResponseCode() == 201) {
				is = connection.getInputStream();
				// 封裝輸入流is,並指定字符
				br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				// 存放數據
				StringBuffer sbf = new StringBuffer();
				String temp = null;
				while ((temp = br.readLine()) != null) {
					sbf.append(temp);
					sbf.append("\r\n");
				}
				result = sbf.toString();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 關閉資源
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (null != is) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			connection.disconnect();// 關閉遠程連接

		}
			
		//System.out.println();
		return result;
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章