Java

How to connect and send a message to an Oracle Advanced Queue (AQ) ?

Most of us are quite familiar with simple JDBC connection that has to do with reading and writing from a table. Most of us usually don’t have a need to send or read from an Advanced Queue that is solely from Oracle but when needed this seems to be such a hassle when not equipped with correct resource.

Here I have shown the simplest and easiest way to connect to an AQ (Oracle Advanced Queue) just using ConnectionFactory and JmsTemplate using Spring Boot App.

import oracle.jms.AQjmsFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.core.JmsTemplate;

import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

@Configuration
@EnableJms
public class OracleAdvancedQueueConfig {


    public void testOracleAdvancedQueueConnection() throws SQLException, JMSException {

        //Same concept applies if using Oracle Exadata

        String dbURL = "jdbc:oracle:thin:username/password@ora-demo.my.test.com:1521:w23";

        Connection conn = DriverManager.getConnection(dbURL);

        ConnectionFactory connectionFactory = AQjmsFactory.getQueueConnectionFactory(dbURL,
                conn.getClientInfo());

        JmsTemplate jmsTemplate = new JmsTemplate();
        jmsTemplate.setSessionTransacted(true);
        jmsTemplate.setConnectionFactory(connectionFactory);
        //Your Oracle Advanced Queue name.
        jmsTemplate.setDefaultDestinationName("MY_SCHEMA.TO_MY_QUEUE_NAME");

        jmsTemplate.convertAndSend("Learn Java");
    }
}

Now if you go into that schema and into that queue table you should see the message sent.

Note: Make sure to use this dependency as this also seems to be a common miss from developers.

        <dependency>
            <groupId>com.oracle.jdbc</groupId>
            <artifactId>ojdbc8</artifactId>
            <version>12.2.0.1</version>
        </dependency>

        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>aqapi</artifactId>
            <version>12.1.0.2.0</version>
        </dependency>

Other dependencies should be pretty straight forward.

Hope this will helps you and save some time.

Leave a Reply