Pregunta

estoy poniendo en práctica un cliente SOAP usando Apache Axis 2. Dado que el cliente SOAP debe manejar pesada número de solicitudes que estoy utilizando un pool de conexiones.

Para hacer eso tenía que establecer una configuración de capa de transporte pocos de mi talón que se generó a partir de un archivo WSDL:

stub._getServiceClient().getOptions().setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE);

MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.getParams().setDefaultMaxConnectionsPerHost(MAX_CONNECTIONS_PER_HOST);
connectionManager.closeIdleConnections(IDLE_CONNECTION_TIMEOUT);
HttpClient httpClient = new HttpClient(connectionManager);

stub._getServiceClient().getOptions().setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);

Mi cliente parece estar funcionando muy bien. Sin embargo, me gustaría saber cómo puedo probar si la agrupación de conexiones está funcionando de manera correcta (es decir, las conexiones creadas solamente se destruyen después del tiempo definido por la constante IDLE_CONNECTION_TIMEOUT). ¿Alguna idea?

¿Fue útil?

Solución

Pseudo-código basado en 3.x JUnit:

  setUp() {
    initialize connection manager;
    initialize connection by creating client;
  }

  tearDown() {
    close connection if necessary;
    close connection manager if necessary;
  }

  testConnectionOpen() {
    assert that connection is open;
    pause for time of idle connection timeout - 1 second;
    assert that connection **is still open**;
  }

  testConnectionClosed() {
    assert that connection is open;
    pause for time of idle connection timeout + 1 second;
    assert that connection **is closed**;
  }

Adición de 1 segundo y restando 1 segundo deben ajustarse dependiendo de la sensibilidad del administrador de conexión.

Otros consejos

Escribir una aplicación de banco de pruebas que hará que un gran número de solicitudes, y afirman que el número de conexiones no es más que MAX_CONNECTIONS. Usted puede ser capaz de comprobar en la última uniendo jconsole o VisualVM al proceso.

También se puede ver en el uso Jakarta JMeter para la generación de carga en la clase / cliente, y luego graficar varios puntos de datos (no sé cómo se ganaría acceso a número de conexiones de cliente creado, sin embargo).

Puede probarlo cambiando los parámetros

  • NO_OF_THREADS
  • POOL_SIZE
  • ENABLE_CONNECTION_POOLING

/** number of concurrent searches */
private static final int NO_OF_THREADS = 20;

/** size of the http connection pool */
private static final int POOL_SIZE = 20;

/** enabling or disabling the connection pool */
private static boolean ENABLE_CONNECTION_POOLING = true;

/** close idle connection time in milliseconds
 * connections will be release if they are idle for this time */
private static int CLOSE_IDLE_CONNECTION_TIME = 1000;

public void test()
{
    init();

    long start = System.currentTimeMillis();

    List<Thread> threads = new ArrayList<Thread>();
    for ( int i = 0; i < NO_OF_THREADS; i++ )
    {
        SimpleThread thread = new SimpleThread();
        thread.start();

        threads.add( thread );
    }

    for ( Thread t : threads )
    {
        try
        {
            t.join();
        }
        catch ( InterruptedException e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    logger.info( "************* Test Finish In *******************" + ( System.currentTimeMillis() - start ) + " ms" );
}

public void init()
{
    super.init();

    try
    {
        long t1 = System.currentTimeMillis();
        stub = new Viva_x0020_external_x0020_API_x0020_for_x0020_partnersStub( endUrl );

        if ( ENABLE_CONNECTION_POOLING )
        {
            stub._getServiceClient().getOptions().setProperty( HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE );
            MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
            connectionManager.getParams().setDefaultMaxConnectionsPerHost( POOL_SIZE );
            connectionManager.closeIdleConnections( CLOSE_IDLE_CONNECTION_TIME );
            HttpClient httpClient = new HttpClient( connectionManager );
            stub._getServiceClient().getOptions().setProperty( HTTPConstants.CACHED_HTTP_CLIENT, httpClient );
        }

        logger.info( "Connection Established in " + ( System.currentTimeMillis() - t1 ) + "ms" );
    }
    catch ( AxisFault e1 )
    {
        e1.printStackTrace();
        fail( "Error on creating the stub" );
    }

    logger.info( "Connection Initialized successfully" );
}

public class SimpleThread extends Thread
{
    public void run()
    {
        search();
    }
}

private static void search()
{
    logger.info( "$$$$$$$$$$$$$ Start the Search $$$$$$$$$$$$$$" );
    GetAirportConnections request = new GetAirportConnections();
    request.setAirportCode( "MTY" );

    GetAirportConnectionsResponse response = null;
    try
    {
        long t1 = System.currentTimeMillis();
        response = stub.getAirportConnections( request, getUserCredentials() );
        logger.info( "Results Retrived in " + ( System.currentTimeMillis() - t1 ) + "ms" );
    }
    catch ( Exception e )
    {
        logger.error( "------------------------- Connection Timeout --------------------------" );
        e.printStackTrace();
        fail( e.getMessage() );
    }

    Airport[] airports = response.getGetAirportConnectionsResult().getAirport();
    logger.info("Number of airports : " + airports.length );
}

}

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top