從一個(gè)腳本談loadrunner的腳本初始化
昨天一個(gè)同事請(qǐng)我一個(gè)問(wèn)題,在下列代碼中如何將
InputStream is 這個(gè)元素只初始化一次呢?
/* * LoadRunner Java script. (Build: _build_number_) * * Script Description: * */ import lrapi.lr; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import com.google.common.io.ByteStreams; import com.jd.jfs.JingdongFileSystem; public class Actions { File file = new File("C:/8K.file"); InputStream is =null; // 返回一個(gè)byte數(shù)組<pre code_snippet_id="145362" snippet_file_name="blog_20140107_2_8044261" name="code" class="java"> byte[] fileBytes = new byte[(int) file.length()]; // 創(chuàng)建一個(gè)數(shù)據(jù)來(lái)保存文件數(shù)據(jù) JingdongFileSystem jfs =new JingdongFileSystem(); public int init() throws Throwable { is = new FileInputStream(file); ByteStreams.readFully(is, fileBytes); is.close(); //jfs = new JingdongFileSystem(); return 0; } //end of init public int action() throws Throwable { try { lr.start_transaction("jfs-w"); String key = jfs.writeBytes(fileBytes); //上傳 System.out.println(key); } catch (Exception e) { e.printStackTrace(); } lr.end_transaction("jfs-w", lr.AUTO); return 0; }//end of action public int end() throws Throwable { return 0; }//end of end } |
我們知道,在loadrunner的java_vuser協(xié)議的腳本中,init方法在每個(gè)vuer初始化的時(shí)候都會(huì)被執(zhí)行一次,換句話說(shuō)N個(gè)用戶就會(huì)被執(zhí)行N次,所以上面的腳本中inputStream對(duì)象會(huì)被初始化N次。我隨即做了如下修改
File file = new File("C:/8K.file"); static InputStream is =null; // 返回一個(gè)byte數(shù)組 <span style="color: #ff0000; "> </span> byte[] fileBytes = new byte[(int) file.length()]; // 創(chuàng)建一個(gè)數(shù)據(jù)來(lái)保存文件數(shù)據(jù) JingdongFileSystem jfs =new JingdongFileSystem(); public int init() throws Throwable { if(is==null){ is = new FileInputStream(file); } ByteStreams.readFully(is, fileBytes); is.close(); //jfs = new JingdongFileSystem(); //初始化 return 0; }//end of init 理論上來(lái)說(shuō),上述代碼實(shí)現(xiàn)了單例模式。但是這個(gè)腳本并發(fā)下無(wú)效。。。 經(jīng)過(guò)和開(kāi)發(fā)探討最終換了以下的代碼來(lái)處理: static { File file = new File("C:/8K.file"); fileBytes = new byte[(int) file.length()]; // 創(chuàng)建一個(gè)數(shù)據(jù)來(lái)保存文件數(shù)據(jù) try { InputStream is = new FileInputStream(file); ByteStreams.readFully(is, fileBytes); is.close(); } catch (Exception e) { e.printStackTrace(); } jfs = new JingdongFileSystem(); } |
靜態(tài)初始化塊:使用static定義,當(dāng)類裝載到系統(tǒng)時(shí)執(zhí)行一次.若在靜態(tài)初始化塊中想初始化變量,那僅能初始化類變量,即static修飾的數(shù)據(jù)成員.
總結(jié)一下:
在java_vuser協(xié)議的腳本中:
1. vuser_init模塊始終不會(huì)被執(zhí)行;
2. init方法會(huì)被初始化合并發(fā)數(shù)相同的次數(shù)
3. 如果想實(shí)現(xiàn)多個(gè)并發(fā)用戶公用一個(gè)變量,請(qǐng)使用靜態(tài)初始化塊。
posted on 2014-02-20 10:54 順其自然EVO 閱讀(1443) 評(píng)論(0) 編輯 收藏 所屬分類: loadrunner