用java编写一个简单的基准测试工具
我想用 java 编写一个简单的基准测试工具,它将启动 x 个线程并总共点击 y 次 url。
它的实际任务部分将向 URL 发出 Web 请求,并发布 XML 文件。
所以我想做的是,分出 50 个线程并继续访问该 url,直到发出 10K 请求。
有人可以解释如何做到这一点,我相信使用执行器服务是正确的方法。
需要考虑的一些事情:
- 一旦线程完成,我猜它会立即运行另一个任务,对吗?
- 我需要线程返回,因为我必须跟踪成功/失败,应该将其存储在哪里(它必须是线程安全的)。
I want to write a simple benchmarking tool in java, that will spin up x threads and hit a url y times in total.
The actual task part of it will make a web request to a url, and post a XML file.
So what I want to do is, spin off 50 threads and keep hitting the url until I have made 10K requests.
Can someone explain how to do this, I believe using the Executor Service is the way to go.
Some things to consider:
- Once a thread is finished, I'm guessing it will immediately run another task correct?
- I need the thread to return as I have to keep track of success/failures, where should this be stored (it has to be thread-safe).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,ExecutorService 是此任务的完美选择:
开始测量时间并简单地向其提交 10K 任务:
考虑使用相同的实例(无状态或线程安全)
SubmitToUrlTask
而不是在每次迭代中创建新的。最后你必须等待执行者完成:
现在停止测量时间。
awaitTermination()
会阻塞,直到所有任务完成,但不会超过给定时间(示例中为 1 毫米分钟)。是的,ExecutorService 是一堆线程和一个任务队列。如果线程没有任何事情可做,它将从队列中获取第一个任务。
您可以使用
Callable
和Future
来跟踪结果。此外,如果您仅使用SubmitToUrlTask
的单个实例,它可以有两个AtomicInteger
类型的变量,用于跟踪成功和失败。如果您不需要跟踪单个结果,这会简单得多。话虽这么说,您是否考虑过使用具有所有这些功能以及更多开箱即用功能的 JMeter ?还有
ab
控制台实用程序。Yes,
ExecutorService
is a perfect choice for this task:Start measuring time and simply submit 10K tasks to it:
Consider using the same instance of (stateless or thread-safe)
SubmitToUrlTask
rather than creating new one in each iteration.At the end you must wait for the executor to finish:
Stop measuring the time now.
awaitTermination()
blocks until all tasks have finished, but not longer than given time (1 mminute in the example).Yes,
ExecutorService
is a bunch of threads and a queue of tasks. If a thread does not have anything to do, it takes first task from the queue.You can use
Callable<Boolean>
andFuture<Boolean>
to track results. Also if you are using only a single instance ofSubmitToUrlTask
, it can have two variables ofAtomicInteger
type, tracking both successes and failures. This is much simpler if you don't need to track individual results.That being said, have you considered using JMeter that has all these functionalities + much more out of the box? There is also
ab
console utility.以下是带注释的源代码,概述了您可以使用的策略:
Here is the annotated source code which outlines a strategy you can use: