Simulate network latency with Apache Tomcat?

2019-02-10 23:49发布

Is it possible to configure Apache Tomcat to simulate network latency that a client would normally have when requesting data from server for requests over localhost? I'm trying to test how the front end of a Java Servlet application will respond to requests that have slow response times.

I know I could go in and add Thread.sleep(100) to all of my Servlet Java source files, but I'd rather have a solution that can be configured in Tomcat rather than in my actual application.

3条回答
老娘就宠你
2楼-- · 2019-02-11 00:41

You can implement a servlet filter and have it intercept all requests. In each of the request you would be doing this Thread.sleep or something else. All requests to your servlets will be delayed.

查看更多
叼着烟拽天下
3楼-- · 2019-02-11 00:45

You can simulate network latency by using a proxy on your localhost which introduces latency, bandwidth restrictions, and even drop packets.

DonsProxy will do the job. Here's a good article describing how to configure it to simulate a user on a poor network.

查看更多
该账号已被封号
4楼-- · 2019-02-11 00:51

This is easily feasible in Tomcat by creating a valve.

Create a class that extends the ValveBase class from tomcat.

The code inside should be something like that:

/**
 * {@inheritDoc}
 */
@Override
public void invoke(final Request request, final Response response) 
                   throws IOException, ServletException {

    if (randomDelay != 0) {
        long delay = minDelay + randomizer.nextInt(randomDelay);
        try {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("sleeping for " + delay + " ms");
            }
            Thread.sleep(delay);
        } catch (InterruptedException e) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("someone wake me up : " + e.getMessage());
            }
        }
    }

    // let's continue !
    getNext().invoke(request, response);
}

Compile it in a jar you'll drop in the tomcat lib directory (usually {catalina.home}/lib).

Finally add the valve declaration in you server.xml:

<Server ...>
  <Service name="Catalina">
   <Engine name="Catalina" defaultHost="localhost">
     (...)
     <Host name="localhost" ...>
       <Valve className="tools.tomcat.RandomDelayValve" />

HIH

查看更多
登录 后发表回答