杰瑞科技汇

Java应用如何用LoadRunner做性能测试?

Of course. The term "Java LoadRunner" refers to using HP LoadRunner (now Micro Focus LoadRunner Professional) to test Java applications. This is a very common use case, as a vast number of business applications are built on Java.

Java应用如何用LoadRunner做性能测试?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering the concepts, architecture, and steps involved.


Core Concepts: How LoadRunner Works with Java

LoadRunner doesn't "run" Java code directly. Instead, it acts as a controller for virtual users (Vusers) that interact with your Java application. There are two primary ways to do this:

A. Protocol-Based Testing (The Traditional Way)

This is the most common method. You choose a protocol that matches your application's architecture. LoadRunner's protocol drivers are essentially pre-built communication libraries.

  • Web/HTTP/HTML Protocol: For testing Java web applications (e.g., running on Tomcat, JBoss, WebLogic) accessed via a browser. This is the most widely used protocol.
  • Web Services (SOAP/REST) Protocol: For testing Java-based web services. Your Java application might expose its functionality as a SOAP or REST API, and LoadRunner can call these services directly without a browser.
  • Citrix or Terminal Server Protocol: For testing Java applications running on a remote desktop or virtualized environment. The Vusers simulate user interactions with the application's GUI on the server.

How it works: The Vuser script records your actions (e.g., clicking a button, submitting a form) and translates them into protocol-specific requests (e.g., HTTP GET/POST requests). When the script is replayed, the Vusers send these requests to the server, simulating real users.

Java应用如何用LoadRunner做性能测试?-图2
(图片来源网络,侵删)

B. LoadRunner Java Vuser (The "True" Java Testing)

This is a more advanced and powerful method. Here, you write a Java application inside LoadRunner to act as the Vuser script.

  • What it is: You write a Java class that implements the VuGen interface. This class contains your test logic, such as making database calls, performing complex calculations, or calling internal Java APIs of your application.
  • When to use it:
    • Testing backend Java processes that don't have a web interface (e.g., batch jobs, message queue consumers, ETL processes).
    • When you need to simulate complex business logic that cannot be recorded with a browser.
    • Testing performance of internal Java APIs (e.g., calling a method in a Java Bean or EJB directly).
    • When you need to leverage external Java libraries (JARs) in your script.

How it works: LoadRunner compiles your Java code and runs it within the Java Virtual Machine (JVM) on each Vuser machine. This gives you full programmatic control over the Vuser's behavior.


Architecture of a Java Load Test

A typical Java load test follows a client-server model:

+-------------------------+      +-------------------------------------+
|  LoadRunner Controller  |----->|   LoadRunner Generator (VuGen)      |
| (Manages the scenario)  |      | (Creates and debugs the Vuser script)|
+-------------------------+      +-------------------------------------+
          |                                  |
          | (Replays script)                 | (Records user actions)
          V                                  V
+-------------------------------------------------------------+
|                      Target System                          |
|  +------------------+    +------------------+    +-----------+ |
|  |   Web Server     |    |   Application   |    |   Database | |
|  | (e.g., Tomcat)   |<-->| Server (Java EE) |<-->| (e.g.,    | |
|  | (handles HTTP)   |    | (Business Logic)|    | Oracle)   | |
|  +------------------+    +------------------+    +-----------+ |
|          ^                     ^                               |
|          | (HTTP Requests)     | (JDBC, JMS, RMI, etc.)        |
|          |                     |                               |
+-------------------------------------------------------------+
  • Controller: The central orchestrator. It defines the test scenario (number of Vusers, duration, etc.), starts the load generators, and collects the results.
  • Generator (VuGen): The tool where you develop and debug your scripts. You can record actions or write code manually.
  • Load Generators: Machines that run the Vuser scripts during a load test. A single machine can run hundreds or thousands of Vusers.
  • Target System: Your Java application and its dependencies (web server, application server, database, etc.).

Step-by-Step Guide: Creating a Java Web Test (HTTP/HTML)

This is the most common scenario for testing a Java web application.

Step 1: Record the Script in VuGen

  1. Open LoadRunner VuGen.
  2. Select Web - HTTP/HTML as the protocol.
  3. Click Create.
  4. In the Recording Wizard, enter the starting URL of your Java application (e.g., http://myapp.company.com/login.jsp).
  5. Configure your browser proxy settings to point to VuGen (it will guide you through this).
  6. Start recording and perform the actions you want to test (e.g., log in, search for an item, add to cart, log out).
  7. Stop the recording. VuGen will generate a script with functions like web_url(), web_submit_data(), etc.

Step 2: Parameterize the Script

Hardcoded values (like user IDs or search terms) are unrealistic. You need to replace them with data from a file.

  1. In the script, find a hardcoded value (e.g., a username).
  2. Right-click on the value and select Replace with a parameter.
  3. Choose a parameter type (e.g., File).
  4. Create a new parameter file (a CSV or text file) with a list of usernames. VuGen will now pick a different value from this file for each Vuser iteration.

Step 3: Add Correlation

This is a critical step for Java applications. When you log in, the server often sends back a unique session ID (like JSESSIONID) that is required for all subsequent requests. If you don't "correlate" this ID, your script will fail after the login step.

  1. While recording, VuGen often automatically detects correlations. Check the "Correlation" view after recording.
  2. If it missed one, you can manually add it. Find the response that contains the session ID (e.g., Set-Cookie: JSESSIONID=ABC123...).
  3. Use the web_reg_save_param() function to capture this value and store it in a variable.
  4. In subsequent requests, use that variable (e.g., {SessionID}) in the headers or URL.

Step 4: Add Pacing and Think Time

  • Think Time: Simulates the time a real user spends reading a page or deciding what to do next. VuGen records this, but you should scale it down (e.g., to 50-70% of the recorded value) to avoid overestating performance.
  • Pacing: Controls the time between iterations of a script's action block (e.g., the time between one login/search cycle and the next).

Step 5: Enhance with Transactions

A "transaction" is a logical business process that you want to measure as a single unit (e.g., "SearchAndBuy").

  1. Wrap the relevant parts of your script with lr_start_transaction("SearchAndBuy"); and lr_end_transaction("SearchAndBuy", LR_AUTO);.
  2. This allows you to see the exact response time for this critical business process in your LoadRunner Analysis reports.

Step 6: Compile the Script

Before running, compile the script to ensure there are no syntax errors. Go to Vuser > Compile or press F5.

Step 7: Create and Run a Scenario in the Controller

  1. Open the Controller.
  2. Create a new Scenario.
  3. Add your script as an action.
  4. Configure the load:
    • Number of Vusers: How many virtual users you want to simulate.
    • Pacing: How often Vusers start a new iteration.
    • Duration: How long the test should run.
  5. Assign the scenario to Load Generators (machines that will run the Vusers).
  6. Start the scenario and monitor the results in real-time.

Key Metrics to Monitor for Java Applications

When you run the test, the Controller will connect to your application servers and databases to gather crucial metrics.

  • Application Server Metrics (via JMX or SNMP):
    • CPU Usage: High CPU can indicate inefficient code or resource contention.
    • Memory Usage (Heap/Non-Heap): Monitor for memory leaks (increasing heap usage over time) or Garbage Collection (GC) pauses. Long GC pauses can cause high response times.
    • Thread Count: The number of active threads. Too many threads can lead to thread contention and poor performance.
    • EJB Pool/Cache Sizes: Are they being exhausted?
  • Database Metrics (via Database Monitors):
    • Database CPU: Is the database a bottleneck?
    • SQL Execution Time: Which queries are slow?
    • Number of Active Connections: Are you running out of database connections?
    • Lock Waits: Are queries waiting for locks?
  • Network Metrics:
    • Network Throughput: Is the network between the load generators and the application server a bottleneck?
  • LoadRunner Metrics:
    • Average/Total Transaction Response Time: The most important metric. Is it within your acceptable limit?
    • Hits per Second / Transactions per Second: How much load is the application handling?
    • Errors per Second: Are Vusers receiving errors (e.g., HTTP 500, connection timeouts)?
    • Vuser Status: How many Vusers are running, passed, failed, or stopped?

Java Vuser Script Example (Code-Based)

This example shows what a simple Java Vuser script looks like. It extends the lrapi.lr class.

// Import necessary LoadRunner classes
import lrapi.lr;
import java.sql.*;
public class JavaVuser extends lr {
    // Define variables to store data
    private String dbUser;
    private String dbPassword;
    private Connection con;
    // The init() method is called once when the Vuser starts
    public int init() {
        lr.log_message("Vuser Initializing...");
        // Get parameters from LoadRunner scenario
        dbUser = lr.eval_string("{DBUser}");
        dbPassword = lr.eval_string("{DBPassword}");
        // Connect to the database
        try {
            // Use a simple JDBC driver for demonstration
            Class.forName("org.postgresql.Driver");
            con = DriverManager.getConnection("jdbc:postgresql://mydb.server:5432/mydb", dbUser, dbPassword);
            lr.log_message("Successfully connected to the database.");
        } catch (Exception e) {
            lr.log_message("Failed to connect to database: " + e.getMessage());
            return -1; // Indicate failure
        }
        return 0;
    }
    // The action() method contains the main test logic
    public int action() {
        lr.start_transaction("DatabaseQuery");
        try {
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM users WHERE status = 'ACTIVE'");
            if (rs.next()) {
                int count = rs.getInt(1);
                lr.log_message("Found " + count + " active users.");
            }
            rs.close();
            stmt.close();
        } catch (SQLException e) {
            lr.log_message("Error during database query: " + e.getMessage());
            lr.end_transaction("DatabaseQuery", lr.FAIL); // End transaction as failed
            return -1;
        }
        lr.end_transaction("DatabaseQuery", lr.PASS); // End transaction as passed
        return 0;
    }
    // The end() method is called once when the Vuser finishes
    public int end() {
        lr.log_message("Vuser Ending...");
        // Close the database connection
        if (con != null) {
            try {
                con.close();
                lr.log_message("Database connection closed.");
            } catch (SQLException e) {
                lr.log_message("Error closing database connection: " + e.getMessage());
            }
        }
        return 0;
    }
}

Summary

Method Best For Pros Cons
Protocol-Based (HTTP/HTML) Testing front-end Java web applications (browser-based). Easiest to set up, records user actions, good for standard web UI testing. Limited to what the protocol can see; can't test internal logic or non-UI components.
Java Vuser Testing back-end Java processes, complex logic, internal APIs, or non-UI apps. Maximum flexibility, can use any Java library, simulates real load on the JVM. Requires Java programming skills, more complex to set up and debug.

For most teams testing a standard Java web application, starting with the Web/HTTP/HTML protocol is the recommended approach. You only move to the Java Vuser method when you need to test something that falls outside the scope of standard web protocols.

分享:
扫描分享到社交APP
上一篇
下一篇