在给定输入的情况下,我如何编写scala脚本来执行以下操作:
url
total requests
total connections (threads)因此,它将使用x个url从给定的threads中request x个网页。
它应该查看请求的响应,以确保它是正常的(而不是失败的请求)。
我猜这在Scala中比在Java中更容易,因为我听说用Scala编写多线程应用程序要容易得多。
所以:
>scalac -url localhost:8080/ -requests 1000 -connections 10会发出1000个请求,但同时有10个线程命中它。
发布于 2011-11-03 00:28:38
我已经编写了一个scala应用程序来做这件事,尽管它是围绕我正在开发的API的压力测试而构建的。使用actors进行并发请求非常容易。一般的想法是,您希望创建一个参与者,当给出一条消息时,执行单个请求。然后创建参与者的多个实例,并使用负载均衡器将请求分发给它们。
下面是一个非常简单的实现,让您了解一下(使用Akka参与者):
case class MakeRequest(url: String)
class RequestActor extends Actor {
//force the actor to run in it's own thread
self.dispatcher = akka.dispatch.Dispatchers.newThreadBasedDispatcher(self)
def receive = {
case MakeRequest(url) => //perform the request
}
}
val totalRequests = 1000
val url = "http://..."
val totalConections = 4
//create one actor per connection and wrap them in a load balancer
val actors = (0 to totalConnections).map{i => actorOf[RequestActor].start}
val requestBalancer = loadBalancerActor(new CyclicIterator(actors))
//start sending requests
for (i <- 0 to totalRequests) {
requestBalancer ! MakeRequest(url)
}
//send a poison pill to stop the actors after they've finished all the requests
requestBalancer ! Broadcast(PoisonPill)
//wait for the actors to finish
while (actors.foldLeft(false){ (b, a) => b || !a.isShutdown}) {
Thread.sleep(300)
}
//stop the load balancer
requestBalancer ! PoisonPill正如您所看到的,我正在向负载均衡器发送MakeRequest消息,负载均衡器将这些消息分发到所有参与者。每个参与者都有一个消息队列,因此单个参与者将一次发出一个请求,但所有参与者将一起并发发出请求。
这个示例没有提供统计响应的方法,您可能会冒着溢出参与者队列的风险,但这些问题很容易修复。我已经使用这个一般的想法来执行广泛的压力测试和基准测试,并取得了巨大的成功。
发布于 2011-11-03 01:52:38
在Scala 2.9+中有一种简单、幼稚的方式,就像丹尼尔建议的那样,忽略线程:
val url: String
val totalRequests: Int
def makeRequest(url: String): Boolean
val requests = (1 to totalRequests).par.map(i => makeRequest(url))
val successes = requests.count(r => r)
val failures = requests.count(r => !r)https://stackoverflow.com/questions/7982853
复制相似问题