代码如下:
/** LoadRunner Java script. (Build: _build_number_)** Script Description:**/import lrapi.lr;import java.sql.*;import java.sql.DriverManager;import com.mysql.jdbc.Connection;public class Actions{private Connection conn ; //把连接放到了start_transaction外,避免每次执行脚本都进行连接public int init() throws Throwable {try{String driver = \"com.mysql.jdbc.Driver\";String url = \"jdbc:mysql://xx.xx.x.xx:3306/test?useSSL=false\"; //mysql连接地址String user = \"root\";String password = \"password\";Class.forName ( driver );conn = (Connection) DriverManager.getConnection ( url, user, password );} catch (Exception e) {e.printStackTrace();}return 0;}//end of initpublic int action() throws Throwable {try{lr.think_time(1); //加入think_time,防止速度过快。。。lr.start_transaction(\"test\");if (!conn.isClosed ()) {//System.out.println ( \"数据库连接成功\" );String sqls = \"SELECT COUNT(1) FROM test WHERE order_no = \'<ORDER_NO>\';\" ;//sql语句PreparedStatement ps = conn.prepareStatement ( sqls );ResultSet rs = ps.executeQuery ();lr.end_transaction(\"test\", lr.AUTO); //自动判断事务成功失败ps.close ();}} catch (Exception e) {// TODO Auto-generated catch blocklr.end_transaction(\"test\", lr.FAIL);e.printStackTrace();}return 0;}//end of actionpublic int end() throws Throwable {conn.close ();return 0;}//end of end}
主要有几个点需要注意:
(一)?useSSL=false警告
String url = \"jdbc:mysql://xx.xx.x.xx:3306/test?useSSL=false\"; //mysql连接地址
这里的?useSSL=false在MySQL5.7版本需要加上,原因是MySQL在高版本需要指明是否进行SSL连接,否则会报一个警告:
Establishing SSL connection without server\'s identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn\'t set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to \'false\'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
(二)执行时间问题
由于查询的sql语句非常快,小于0.001秒,已经达到了loadrunner响应时间的最小识别单位,所以把数据库的连接放在了外面init初始化里,否则数据库连接不能及时释放,会产生大量的TIME_WAIT端口,可以使用此命令查看是否存在TIME_WAIT端口:
netstat -n | awk \'/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}\'
,导致响应时间逐渐升高,影响性能。
(三)执行次数
在lr的Run-time-setting设置Iteration Count,number可多设置一些,保证一次连接可以执行多个SQL,另外还可以调节thinktime,将TPS控制在一定范围内。