검색

이 콘텐츠는 선택한 언어로 제공되지 않습니다.

Using the AMQ JMS Pool Library

download PDF
Red Hat AMQ 2021.Q3

For Use with AMQ Clients 2.10

Abstract

This guide describes how to install and configure the library, run hands-on examples, and use your client with other AMQ components.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. We are beginning with these four terms: master, slave, blacklist, and whitelist. Because of the enormity of this endeavor, these changes will be implemented gradually over several upcoming releases. For more details, see our CTO Chris Wright’s message.

Chapter 1. Overview

AMQ JMS Pool is a library that provides caching of JMS connections, sessions, and message producers. It enables reuse of connection resources beyond the standard lifecycle defined by the JMS API.

AMQ JMS Pool operates as a standard JMS ConnectionFactory instance that wraps the ConnectionFactory of your chosen JMS provider and manages the lifetime of Connection objects from that provider based on the configuration of the JMS pool. It can be configured to share one or more connections among callers to the pool createConnection() methods.

AMQ JMS Pool is part of AMQ Clients, a suite of messaging libraries supporting multiple languages and platforms. For an overview of the clients, see AMQ Clients Overview. For information about this release, see AMQ Clients 2.10 Release Notes.

AMQ JMS Pool is based on the Pooled JMS messaging library.

1.1. Key features

  • JMS 1.1 and 2.0 compatible
  • Automatic reconnect
  • Configurable connection and session pool sizes

1.2. Supported standards and protocols

AMQ JMS Pool supports version 2.0 of the Java Message Service API.

1.3. Supported configurations

Refer to Red Hat AMQ 7 Supported Configurations on the Red Hat Customer Portal for current information regarding AMQ JMS Pool supported configurations.

1.4. Document conventions

The sudo command

In this document, sudo is used for any command that requires root privileges. Exercise caution when using sudo because any changes can affect the entire system. For more information about sudo, see Using the sudo command.

File paths

In this document, all file paths are valid for Linux, UNIX, and similar operating systems (for example, /home/andrea). On Microsoft Windows, you must use the equivalent Windows paths (for example, C:\Users\andrea).

Variable text

This document contains code blocks with variables that you must replace with values specific to your environment. Variable text is enclosed in arrow braces and styled as italic monospace. For example, in the following command, replace <project-dir> with the value for your environment:

$ cd <project-dir>

Chapter 2. Installation

This chapter guides you through the steps to install AMQ JMS Pool in your environment.

2.1. Prerequisites

  • You must have a subscription to access AMQ release files and repositories.
  • To build programs with AMQ JMS Pool, you must install Apache Maven.
  • To use AMQ JMS Pool, you must install Java.

2.2. Using the Red Hat Maven repository

Configure your Maven environment to download the client library from the Red Hat Maven repository.

Procedure

  1. Add the Red Hat repository to your Maven settings or POM file. For example configuration files, see Section B.1, “Using the online repository”.

    <repository>
      <id>red-hat-ga</id>
      <url>https://maven.repository.redhat.com/ga</url>
    </repository>
  2. Add the library dependency to your POM file.

    <dependency>
      <groupId>org.messaginghub</groupId>
      <artifactId>pooled-jms</artifactId>
      <version>2.0.0.redhat-00001</version>
    </dependency>

The client is now available in your Maven project.

2.3. Installing a local Maven repository

As an alternative to the online repository, AMQ JMS Pool can be installed to your local filesystem as a file-based Maven repository.

Procedure

  1. Use your subscription to download the AMQ Clients 2.10.0 JMS Pool Maven repository .zip file.
  2. Extract the file contents into a directory of your choosing.

    On Linux or UNIX, use the unzip command to extract the file contents.

    $ unzip amq-clients-2.10.0-jms-pool-maven-repository.zip

    On Windows, right-click the .zip file and select Extract All.

  3. Configure Maven to use the repository in the maven-repository directory inside the extracted install directory. For more information, see Section B.2, “Using a local repository”.

2.4. Installing the examples

Procedure

  1. Use the git clone command to clone the source repository to a local directory named pooled-jms:

    $ git clone https://github.com/messaginghub/pooled-jms.git pooled-jms
  2. Change to the pooled-jms directory and use the git checkout command to switch to the 2.0.0 branch:

    $ cd pooled-jms
    $ git checkout 2.0.0

The resulting local directory is referred to as <source-dir> throughout this document.

Chapter 3. Getting started

This chapter guides you through the steps to set up your environment and run a simple messaging program.

3.1. Prerequisites

3.2. Running Hello World

The Hello World example calls createConnection() for each character of the string "Hello World", transferring one at a time. Because AMQ JMS Pool is in use, each call reuses the same underlying JMS Connection object.

Procedure

  1. Use Maven to build the examples by running the following command in the <source-dir>/pooled-jms-examples directory.

    $ mvn clean package dependency:copy-dependencies -DincludeScope=runtime -DskipTests

    The addition of dependency:copy-dependencies results in the dependencies being copied into the target/dependency directory.

  2. Use the java command to run the example.

    On Linux or UNIX:

    $ java -cp "target/classes:target/dependency/*" org.messaginghub.jms.example.HelloWorld

    On Windows:

    > java -cp "target\classes;target\dependency\*" org.messaginghub.jms.example.HelloWorld

Running it on Linux results in the following output:

$ java -cp "target/classes/:target/dependency/*" org.messaginghub.jms.example.HelloWorld
2018-05-17 11:04:23,393 [main           ] - INFO  JmsPoolConnectionFactory       - Provided ConnectionFactory is JMS 2.0+ capable.
2018-05-17 11:04:23,715 [localhost:5672]] - INFO  SaslMechanismFinder            - Best match for SASL auth was: SASL-ANONYMOUS
2018-05-17 11:04:23,739 [localhost:5672]] - INFO  JmsConnection                  - Connection ID:104dfd29-d18d-4bf5-aab9-a53660f58633:1 connected to remote Broker: amqp://localhost:5672
Hello World

The source code for the example is in the <source-dir>/pooled-jms-examples/src/main/java directory. The JNDI and logging configuration is in the <source-dir>/pooled-jms-examples/src/main/resources directory.

Chapter 4. Configuration

The AMQ JMS Pool ConnectionFactory implementation exposes several configuration options that control the behavior of the pool and the JMS resources it manages.

The configuration options are exposed as set methods on the JmsPoolConnectionFactory object. For example, the maxConnections option is set using the setMaxConnections(int) method.

4.1. Connection options

These options affect how the JMS pool creates and manages the connections in the pool.

The pooled ConnectionFactory creates a pool of connections for each user and password combination used to create a connection, plus a separate pool for those without a username or password. If you require a more fine-grained division of connections into pools, you must explicitly create distinct pool instances.

maxConnections
The maximum number of connections for a single pool. The default is 1.
connectionIdleTimeout
The time in milliseconds before a connection not currently on loan can be evicted from the pool. The default is 30 seconds. A value of 0 disables the timeout.
connectionCheckInterval
The time in milliseconds between periodic checks for expired connections. The default is 0, meaning the check is disabled.
useProviderJMSContext

If enabled, use the JMSContext classes of the underlying JMS provider. It is disabled by default.

In normal operation, the pool uses its own generic JMSContext implementation to wrap connections from the pool instead of using the provider implementation. The generic implementation might have limitations the provider implementation does not. However, when enabled, connections from the JMSContext API are not managed by the pool.

4.2. Session options

These options affect the behavior of sessions that are created from pooled connections.

maxSessionsPerConnection

The maximum number of sessions for each connection. The default is 500. A negative value removes any limit.

If the limit is exceeded, createSession() either blocks or throws an exception, depending on configuration.

blockIfSessionPoolIsFull

If enabled, block createSession() until a session becomes available in the pool. It is enabled by default.

If disabled, calls to createSession() throw an IllegalStateException if no session is available.

blockIfSessionPoolIsFullTimeout
The time in milliseconds before a blocked call to createSession() throws an IllegalStateException. The default is -1, meaning the call blocks forever.
useAnonymousProducers

If enabled, use a single anonymous JMS MessageProducer for all calls to createProducer(). It is enabled by default.

In rare cases, this behavior is undesirable. If disabled, every call to createProducer() results in a new MessageProducer instance.

Chapter 5. Examples

This chapter demonstrates the use of AMQ JMS Pool through example programs.

For more examples, see the Pooled JMS examples.

5.1. Prerequisites

5.2. Establishing a connection

This example creates a new connection pool, binds it to a connection factory, and uses the pool to create a new connection.

Example: Establishing a connection - Connect.java

package net.example;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import org.apache.qpid.jms.JmsConnectionFactory;
import org.messaginghub.pooled.jms.JmsPoolConnectionFactory;

public class Connect {
    public static void main(String[] args) throws Exception {
        if (args.length != 1) {
            System.err.println("Usage: Connect <connection-uri>");
            System.exit(1);
        }

        String connUri = args[0];

        ConnectionFactory factory = new JmsConnectionFactory(connUri);
        JmsPoolConnectionFactory pool = new JmsPoolConnectionFactory();

        try {
            pool.setConnectionFactory(factory);

            Connection conn = pool.createConnection();

            conn.start();

            try {
                System.out.println("CONNECT: Connected to '" + connUri + "'");
            } finally {
                conn.close();
            }
        } finally {
            pool.stop();
        }
    }
}

5.3. Configuring the pool

This example demonstrates setting connection and session configuration options.

Example: Configuring the pool - ConnectWithConfiguration.java

package net.example;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import org.apache.qpid.jms.JmsConnectionFactory;
import org.messaginghub.pooled.jms.JmsPoolConnectionFactory;

public class ConnectWithConfiguration {
    public static void main(String[] args) throws Exception {
        if (args.length != 1) {
            System.err.println("Usage: ConnectWithConfiguration <connection-uri>");
            System.exit(1);
        }

        String connUri = args[0];

        ConnectionFactory factory = new JmsConnectionFactory(connUri);
        JmsPoolConnectionFactory pool = new JmsPoolConnectionFactory();

        try {
            pool.setConnectionFactory(factory);

            // Set the max connections per user to a higher value
            pool.setMaxConnections(5);

            // Create a MessageProducer for each createProducer() call
            pool.setUseAnonymousProducers(false);

            Connection conn = pool.createConnection();

            conn.start();

            try {
                System.out.println("CONNECT: Connected to '" + connUri + "'");
            } finally {
                conn.close();
            }
        } finally {
            pool.stop();
        }
    }
}

5.4. Running the examples

To compile and run the example programs, use the following procedure.

Procedure

  1. Create a new project directory. This is referred to as <project-dir> in the steps that follow.
  2. Copy the example Java listings to the following locations:

    <project-dir>/src/main/java/net/example/Connect.java
    <project-dir>/src/main/java/net/example/ConnectWithConfiguration.java
  3. Use a text editor to create a new <project-dir>/pom.xml file. Add the following XML to it:

    <project>
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>net.example</groupId>
      <artifactId>example</artifactId>
      <version>1.0.0-SNAPSHOT</version>
    
      <dependencies>
        <dependency>
          <groupId>org.messaginghub</groupId>
          <artifactId>pooled-jms</artifactId>
          <version>2.0.0.redhat-00001</version>
        </dependency>
        <dependency>
          <groupId>org.apache.qpid</groupId>
          <artifactId>qpid-jms-client</artifactId>
          <version>${qpid-jms-version}</version>
        </dependency>
      </dependencies>
    </project>

    Replace ${qpid-jms-version} with your preferred Qpid JMS version.

  4. Change to the project directory and use the mvn command to compile the program.

    mvn clean package dependency:copy-dependencies -DincludeScope=runtime -DskipTests

    The addition of dependency:copy-dependencies results in the dependencies being copied into the target/dependency directory.

  5. Use the java command to run the program.

    On Linux or UNIX:

    java -cp "target/classes:target/dependency/*" net.example.Connect amqp://localhost

    On Windows:

    java -cp "target\classes;target\dependency\*" net.example.Connect amqp://localhost

These sample commands run the Connect example. To run another example, replace Connect with the class name of your desired example.

Running the Connect example on Linux results in the following output:

$ java -cp "target/classes:target/dependency/*" net.example.Connect amqp://localhost
CONNECT: Connected to 'amqp://localhost'

Appendix A. Using your subscription

AMQ is provided through a software subscription. To manage your subscriptions, access your account at the Red Hat Customer Portal.

A.1. Accessing your account

Procedure

  1. Go to access.redhat.com.
  2. If you do not already have an account, create one.
  3. Log in to your account.

A.2. Activating a subscription

Procedure

  1. Go to access.redhat.com.
  2. Navigate to My Subscriptions.
  3. Navigate to Activate a subscription and enter your 16-digit activation number.

A.3. Downloading release files

To access .zip, .tar.gz, and other release files, use the customer portal to find the relevant files for download. If you are using RPM packages or the Red Hat Maven repository, this step is not required.

Procedure

  1. Open a browser and log in to the Red Hat Customer Portal Product Downloads page at access.redhat.com/downloads.
  2. Locate the Red Hat AMQ entries in the INTEGRATION AND AUTOMATION category.
  3. Select the desired AMQ product. The Software Downloads page opens.
  4. Click the Download link for your component.

A.4. Registering your system for packages

To install RPM packages for this product on Red Hat Enterprise Linux, your system must be registered. If you are using downloaded release files, this step is not required.

Procedure

  1. Go to access.redhat.com.
  2. Navigate to Registration Assistant.
  3. Select your OS version and continue to the next page.
  4. Use the listed command in your system terminal to complete the registration.

For more information about registering your system, see one of the following resources:

Appendix B. Using Red Hat Maven repositories

This section describes how to use Red Hat-provided Maven repositories in your software.

B.1. Using the online repository

Red Hat maintains a central Maven repository for use with your Maven-based projects. For more information, see the repository welcome page.

There are two ways to configure Maven to use the Red Hat repository:

Adding the repository to your Maven settings

This method of configuration applies to all Maven projects owned by your user, as long as your POM file does not override the repository configuration and the included profile is enabled.

Procedure

  1. Locate the Maven settings.xml file. It is usually inside the .m2 directory in the user home directory. If the file does not exist, use a text editor to create it.

    On Linux or UNIX:

    /home/<username>/.m2/settings.xml

    On Windows:

    C:\Users\<username>\.m2\settings.xml
  2. Add a new profile containing the Red Hat repository to the profiles element of the settings.xml file, as in the following example:

    Example: A Maven settings.xml file containing the Red Hat repository

    <settings>
      <profiles>
        <profile>
          <id>red-hat</id>
          <repositories>
            <repository>
              <id>red-hat-ga</id>
              <url>https://maven.repository.redhat.com/ga</url>
            </repository>
          </repositories>
          <pluginRepositories>
            <pluginRepository>
              <id>red-hat-ga</id>
              <url>https://maven.repository.redhat.com/ga</url>
              <releases>
                <enabled>true</enabled>
              </releases>
              <snapshots>
                <enabled>false</enabled>
              </snapshots>
            </pluginRepository>
          </pluginRepositories>
        </profile>
      </profiles>
      <activeProfiles>
        <activeProfile>red-hat</activeProfile>
      </activeProfiles>
    </settings>

For more information about Maven configuration, see the Maven settings reference.

Adding the repository to your POM file

To configure a repository directly in your project, add a new entry to the repositories element of your POM file, as in the following example:

Example: A Maven pom.xml file containing the Red Hat repository

<project>
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example</groupId>
  <artifactId>example-app</artifactId>
  <version>1.0.0</version>

  <repositories>
    <repository>
      <id>red-hat-ga</id>
      <url>https://maven.repository.redhat.com/ga</url>
    </repository>
  </repositories>
</project>

For more information about POM file configuration, see the Maven POM reference.

B.2. Using a local repository

Red Hat provides file-based Maven repositories for some of its components. These are delivered as downloadable archives that you can extract to your local filesystem.

To configure Maven to use a locally extracted repository, apply the following XML in your Maven settings or POM file:

<repository>
  <id>red-hat-local</id>
  <url>${repository-url}</url>
</repository>

${repository-url} must be a file URL containing the local filesystem path of the extracted repository.

Table B.1. Example URLs for local Maven repositories
Operating systemFilesystem pathURL

Linux or UNIX

/home/alice/maven-repository

file:/home/alice/maven-repository

Windows

C:\repos\red-hat

file:C:\repos\red-hat

Appendix C. Using AMQ Broker with the examples

The AMQ JMS Pool examples require a running message broker with a queue named queue. Use the procedures below to install and start the broker and define the queue.

C.1. Installing the broker

Follow the instructions in Getting Started with AMQ Broker to install the broker and create a broker instance. Enable anonymous access.

The following procedures refer to the location of the broker instance as <broker-instance-dir>.

C.2. Starting the broker

Procedure

  1. Use the artemis run command to start the broker.

    $ <broker-instance-dir>/bin/artemis run
  2. Check the console output for any critical errors logged during startup. The broker logs Server is now live when it is ready.

    $ example-broker/bin/artemis run
               __  __  ____    ____            _
         /\   |  \/  |/ __ \  |  _ \          | |
        /  \  | \  / | |  | | | |_) |_ __ ___ | | _____ _ __
       / /\ \ | |\/| | |  | | |  _ <| '__/ _ \| |/ / _ \ '__|
      / ____ \| |  | | |__| | | |_) | | | (_) |   <  __/ |
     /_/    \_\_|  |_|\___\_\ |____/|_|  \___/|_|\_\___|_|
    
     Red Hat AMQ <version>
    
    2020-06-03 12:12:11,807 INFO  [org.apache.activemq.artemis.integration.bootstrap] AMQ101000: Starting ActiveMQ Artemis Server
    ...
    2020-06-03 12:12:12,336 INFO  [org.apache.activemq.artemis.core.server] AMQ221007: Server is now live
    ...

C.3. Creating a queue

In a new terminal, use the artemis queue command to create a queue named queue.

$ <broker-instance-dir>/bin/artemis queue create --name queue --address queue --auto-create-address --anycast

You are prompted to answer a series of yes or no questions. Answer N for no to all of them.

Once the queue is created, the broker is ready for use with the example programs.

C.4. Stopping the broker

When you are done running the examples, use the artemis stop command to stop the broker.

$ <broker-instance-dir>/bin/artemis stop

Revised on 2021-08-24 14:27:43 UTC

Legal Notice

Copyright © 2021 Red Hat, Inc.
The text of and illustrations in this document are licensed by Red Hat under a Creative Commons Attribution–Share Alike 3.0 Unported license ("CC-BY-SA"). An explanation of CC-BY-SA is available at http://creativecommons.org/licenses/by-sa/3.0/. In accordance with CC-BY-SA, if you distribute this document or an adaptation of it, you must provide the URL for the original version.
Red Hat, as the licensor of this document, waives the right to enforce, and agrees not to assert, Section 4d of CC-BY-SA to the fullest extent permitted by applicable law.
Red Hat, Red Hat Enterprise Linux, the Shadowman logo, the Red Hat logo, JBoss, OpenShift, Fedora, the Infinity logo, and RHCE are trademarks of Red Hat, Inc., registered in the United States and other countries.
Linux® is the registered trademark of Linus Torvalds in the United States and other countries.
Java® is a registered trademark of Oracle and/or its affiliates.
XFS® is a trademark of Silicon Graphics International Corp. or its subsidiaries in the United States and/or other countries.
MySQL® is a registered trademark of MySQL AB in the United States, the European Union and other countries.
Node.js® is an official trademark of Joyent. Red Hat is not formally related to or endorsed by the official Joyent Node.js open source or commercial project.
The OpenStack® Word Mark and OpenStack logo are either registered trademarks/service marks or trademarks/service marks of the OpenStack Foundation, in the United States and other countries and are used with the OpenStack Foundation's permission. We are not affiliated with, endorsed or sponsored by the OpenStack Foundation, or the OpenStack community.
All other trademarks are the property of their respective owners.
Red Hat logoGithubRedditYoutubeTwitter

자세한 정보

평가판, 구매 및 판매

커뮤니티

Red Hat 문서 정보

Red Hat을 사용하는 고객은 신뢰할 수 있는 콘텐츠가 포함된 제품과 서비스를 통해 혁신하고 목표를 달성할 수 있습니다.

보다 포괄적 수용을 위한 오픈 소스 용어 교체

Red Hat은 코드, 문서, 웹 속성에서 문제가 있는 언어를 교체하기 위해 최선을 다하고 있습니다. 자세한 내용은 다음을 참조하세요.Red Hat 블로그.

Red Hat 소개

Red Hat은 기업이 핵심 데이터 센터에서 네트워크 에지에 이르기까지 플랫폼과 환경 전반에서 더 쉽게 작업할 수 있도록 강화된 솔루션을 제공합니다.

© 2024 Red Hat, Inc.