先來看看官方解釋:
The JSR223 Sampler allows JSR223 script code to be used to perform a sample or some computation required to create/update variables.
JSR223 Test Elements using Script file or Script text + checked Cache compiled script if available are now compiled if ScriptEngine supports this feature, this enables great performance enhancements.
JMeter processes function and variable references before passing the script field to the interpreter, so the references will only be resolved once. Variable and function references in script files will be passed verbatim to the interpreter, which is likely to cause a syntax error. In order to use runtime variables, please use the appropriate props methods, e.g.
props.get("START.HMS"); props.put("PROP1","1234");
實戰內容
需求:根據每天的日期,線程組進行遞增+1,
根據線程組的遞增,日期也隨着遞增,從而出現多少個線程,就在當前數量上遞增日期,
比如當前日期2019-08-07,線程組1,那么就在當前日期+1的日期上進行插入一條數據;
如果需要壓測 10個線程執行,那么就會在當前日期+10天之后,每一天都會插入數據,
var n=${__threadNum}; function dateAdd(startDate,n) { startDate = new Date(startDate); startDate = +startDate + 1000*60*60*24*n; startDate = new Date(startDate); var nextStartDate = startDate.getFullYear()+"-"+(startDate.getMonth()+1)+"-"+startDate.getDate(); return nextStartDate; } vars.put('n',${__threadNum}); a = dateAdd('2019-08-07',n); vars.put('a',a);
如果還不明白可以直接debug看看數據就清楚了
首先,線程組壓測10個線程
JSR223 Sampler 定義好日期的開始時間
核對每一次debug的結果
第一次請求
第一次返回
第二次請求
第二次返回
即,當設置了10個線程壓測,每跑一次線程,“n”就會根據線程數來定義值
第一個線程執行,“n”就是1
第二個線程執行,“n”就是2
......
以此類推
第10次,就是n=10,那么值就是當前設定的日期上+10
最終,在請求中的鍵值對添加上調用的參數即可
"timeFrom":"${a} 11:59:00","timeTo":"${a} 12:39:00"
參數 “${a}” 對應的就是日期
這樣就可以實現批量根據日期跑數據了