You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JMeter中按固定间隔重新生成auth_token?

Great question—handling short-lived auth tokens is a super common pain point in performance testing, and JMeter has a few reliable ways to automate the refresh process. Let me break down the most practical methods for you:

Method 1: Dedicated Thread Group for Token Refresh (Most Straightforward)

This approach keeps token management separate from your main test traffic, so it doesn't interfere with your performance metrics. Here's how to set it up:

  • Create a new Thread Group specifically for token generation. Set the number of threads to 1 and loop count to Forever (or adjust based on your total test duration).
  • Add an HTTP Request sampler to this thread group that calls your token-generation API.
  • Add a JSON Extractor (or Regular Expression Extractor, depending on your API's response format) to pull the auth_token from the response. Store it in a global property using the __setProperty function:
    ${__setProperty(global_auth_token, ${extracted_auth_token},)}
    
    (Replace ${extracted_auth_token} with the variable name you used in your extractor.)
  • Add a Constant Timer to this thread group, set to 3540000 milliseconds (that's 59 minutes—we refresh a minute early to avoid any race conditions where the token expires mid-request).
  • In your main business test thread group, reference the global token using ${__P(global_auth_token,)} in your HTTP headers or request parameters.

This method is clean and easy to maintain, especially for longer test runs.

Method 2: JSR223 PreProcessor for Per-Request Token Checks

If you prefer not to use a separate thread group, you can add a check before every request that needs the token:

  • First, set up an initial token in a SetUp Thread Group: add an HTTP request to get your first token, extract it, and store both the token and its generation time:
    • Use an extractor to save auth_token as a variable.
    • Add a JSR223 PostProcessor with this code to record when the token was created:
      vars.put("token_generated_time", String.valueOf(System.currentTimeMillis()))
      
  • For every HTTP request that requires the token, add a JSR223 PreProcessor with this Groovy code to check if a refresh is needed:
    long currentTime = System.currentTimeMillis()
    long tokenGeneratedTime = vars.get("token_generated_time") != null ? Long.parseLong(vars.get("token_generated_time")) : 0
    // Refresh 1 minute before expiration (adjust if needed)
    long refreshThreshold = 59 * 60 * 1000
    
    if (currentTime - tokenGeneratedTime > refreshThreshold || vars.get("auth_token") == null) {
        // Trigger the token-generation sampler (replace "Get Auth Token" with your sampler's name)
        def tokenSampler = ctx.getSamplerCache().get("Get Auth Token")
        if (tokenSampler != null) {
            tokenSampler.sample(null)
            // Update the generation time after refresh
            vars.put("token_generated_time", String.valueOf(currentTime))
            log.info("Refreshed auth token - new generation time: ${currentTime}")
        }
    }
    
  • Make sure your token-generation sampler is named exactly as referenced in the code (e.g., "Get Auth Token") so the preprocessor can find it.

This method is great if you want token checks tied directly to your request flow, and works well for smaller test suites.

Key Tips for Success

  • Refresh early: Always refresh the token 1-2 minutes before it expires to account for network latency or API delays—you don't want a request to fail because the token expired mid-flight.
  • Use global properties: When sharing tokens across thread groups, rely on __setProperty and __P instead of regular variables, since regular variables are thread-group-specific.
  • Debug with logs: Add log.info() statements to your JSR223 scripts to verify when tokens are being refreshed—this helps troubleshoot if something isn't working as expected.

内容的提问来源于stack exchange,提问作者dishant patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:56:18