Saturday, October 6, 2018

ActiveMQ Consumer and producer

This tutorial will help you create simple consumer and producer app that uses ActiveMQ

Start AciveMQ server by executing activemq.bat which located installation path

Path:C:\Software\apache-activemq-5.15.6-bin\apache-activemq-5.15.6\bin\win64\activemq.bat


 

Folder structure

 

Files used

i). jndi.properties
ii).Producer1.java
iii.)Consumer1.java

JNDI.properties

# START SNIPPET: jndi

java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory

# use the following property to configure the default connector

java.naming.provider.url = vm://localhost

# use the following property to specify the JNDI name the connection factory

# should appear as.

#connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry

# register some queues in JNDI using the form

# queue.[jndiName] = [physicalName]

queue.MyQueue = example.TESTQueue

# register some topics in JNDI using the form

# topic.[jndiName] = [physicalName]

topic.MyTopic = example.MyTopic

# END SNIPPET: jndi
 

 Producer1.java

package com.activemqjndi;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.log4j.BasicConfigurator;

public class Producer1 {

       public Producer1() throws JMSException, NamingException, IOException {

             // Obtain a JNDI connection
             Properties jndiParameters = new Properties();
             jndiParameters.load(new FileInputStream("C:/Learning/MQQUEQE/src/com/activemqjndi/jndi.properties"));
             jndiParameters.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
             jndiParameters.put(Context.PROVIDER_URL, "tcp://localhost:61616");
             InitialContext jndi = new InitialContext(jndiParameters);

             // Look up a JMS connection factory
             ConnectionFactory conFactory = (ConnectionFactory) jndi

                           .lookup("ConnectionFactory");

             Connection connection;
             // Getting JMS connection from the server and starting it
             connection = conFactory.createConnection();
             try {

                    connection.start();

                    // JMS messages are sent and received using a Session. We will
                    // create here a non-transactional session object. If you want
                    // to use transactions you should set the first parameter to 'true'

                    Session session = connection.createSession(false,

                                 Session.AUTO_ACKNOWLEDGE);

                    Destination destination = (Destination) jndi.lookup("MyQueue");
                    // MessageProducer is used for sending messages (as opposed
                    // to MessageConsumer which is used for receiving them)

                    MessageProducer producer = session.createProducer(destination);

                    // We will send a small text message
                    Properties prop = new Properties();
                    prop.load(new FileInputStream("C:/Learning/MQQUEQE/src/com/message/message.txt"));
                    String message = prop.getProperty("msg");
                    TextMessage txtmessage = session.createTextMessage(message);

                    // Here we are sending the message!

                    producer.send(txtmessage);

                    System.out.println("Sent message '" + txtmessage.getText() + "'");

             } finally {

                    connection.close();

             }

       }

       public static void main(String[] args) throws JMSException, IOException {

             try {

                    BasicConfigurator.configure();

                    new Producer1();

             } catch (NamingException e) {

                    e.printStackTrace();

             }

       }

}
 



 You can find message sent by Producer1

Link:
http://localhost:8161/admin/queues.jsp
Go to Queues

 



 Message Details:

 




 Now consume message by Consumer1 program


 Consumer1.java

package com.activemqjndi;

import javax.jms.*;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.log4j.BasicConfigurator;

public class Consumer1 {

 // URL of the JMS server
 private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;

 // Name of the queue we will receive messages from
 private static String subject = "example.TESTQueue";

 public static void main(String[] args) throws JMSException {

  BasicConfigurator.configure();
  // Getting JMS connection from the server
  ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
  Connection connection = connectionFactory.createConnection();
  connection.start();

  // Creating session for seding messages
  Session session = connection.createSession(false,
  Session.AUTO_ACKNOWLEDGE);

  // Getting the queue
  Destination destination = session.createQueue(subject);

  // MessageConsumer is used for receiving (consuming) messages
  MessageConsumer consumer = session.createConsumer(destination);

  // Here we receive the message.
  // By default this call is blocking, which means it will wait
  // for a message to arrive on the queue.

  Message message = consumer.receive();

  // There are many types of Message and TextMessage
  // is just one of them. Producer sent us a TextMessage
  // so we must cast to it to get access to its .getText()
  // method.

  if (message instanceof TextMessage) {

   TextMessage textMessage = (TextMessage) message;

   System.out.println("Received message '" + textMessage.getText()

     + "'");

  }

  connection.close();

 }

}




 
 














WebSphere MQ Consumer and producer

Put messages in IBM MQ using Java

This tutorial will help you create simple consumer and producer app that uses Websphere MQ

 Directory structure:

Input text file for your message

message.txt


msg=Message created by SimpleJMSProducer

 
SimpleJMSProducer

 

package com.mq;

import com.ibm.mq.MQException;
import com.ibm.mq.constants.CMQC;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

/**
 * This class is an example of JMS Client. Using sendMsg() method you can send a
 * message to the IBM MQ
 *
 * To run this example you need com.ibm.mq.jar and com.ibm.mq.jmqi.jar
 *
 *
 */
public class SimpleJMSProducer {
    public void sendMsg(String msg) {
        MQQueueManager queueManager = null;
        MQMessage mqMessage = null;
        MQPutMessageOptions myPMO = null;

        try {

            // creating queue manager
            queueManager = new MQQueueManager("QMGR1");

            // creating queue`

            MQQueue queue = queueManager.accessQueue("MQ.REQUEST", CMQC.MQOO_OUTPUT);

            // configuring message encoding, character set, and format

            mqMessage = new MQMessage();
            mqMessage.encoding = new Integer("546");
            mqMessage.characterSet = new Integer("1208");
            mqMessage.format = "MQSTR";

            // sending message

            mqMessage.writeString(msg);
            myPMO = new MQPutMessageOptions();
            queue.put(mqMessage, myPMO);

            // Closing Queue after putting message
            queue.close();

        } catch (MQException | NumberFormatException | IOException je) {
            je.printStackTrace(System.err);
        } finally {
            if (queueManager != null)
                try {
                    // Disconnecting queue manager
                    queueManager.disconnect();
                } catch (MQException ex) {
                    ex.printStackTrace(System.err);
                }
        }
    }

    public static void main(String[] args) throws FileNotFoundException, IOException {
        Properties prop = new Properties();
        prop.load(new FileInputStream("C:/Learning/MQQUEQE/src/com/message/message.txt"));
        String message = prop.getProperty("msg");
        new SimpleJMSProducer().sendMsg(message);
        System.out.println(message);

    }
}

You will find message sent by above program in MQ by browsing queque( MQ.REQUEST )


 

 SimpleJMSProducer

package com.mq;

import com.ibm.mq.MQException;
import com.ibm.mq.constants.CMQC;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

/**
 * This class is an example of JMS Client. Using sendMsg() method you can send a
 * message to the IBM MQ
 *
 * To run this example you need com.ibm.mq.jar and com.ibm.mq.jmqi.jar
 *
 *
 */
public class SimpleJMSProducer {
    public void sendMsg(String msg) {
        MQQueueManager queueManager = null;
        MQMessage mqMessage = null;
        MQPutMessageOptions myPMO = null;

        try {

            // creating queue manager
            queueManager = new MQQueueManager("QMGR1");

            // creating queue`

            MQQueue queue = queueManager.accessQueue("MQ.REQUEST", CMQC.MQOO_OUTPUT);

            // configuring message encoding, character set, and format

            mqMessage = new MQMessage();
            mqMessage.encoding = new Integer("546");
            mqMessage.characterSet = new Integer("1208");
            mqMessage.format = "MQSTR";

            // sending message

            mqMessage.writeString(msg);
            myPMO = new MQPutMessageOptions();
            queue.put(mqMessage, myPMO);

            // Closing Queue after putting message
            queue.close();

        } catch (MQException | NumberFormatException | IOException je) {
            je.printStackTrace(System.err);
        } finally {
            if (queueManager != null)
                try {
                    // Disconnecting queue manager
                    queueManager.disconnect();
                } catch (MQException ex) {
                    ex.printStackTrace(System.err);
                }
        }
    }

    public static void main(String[] args) throws FileNotFoundException, IOException {
        Properties prop = new Properties();
        prop.load(new FileInputStream("C:/Learning/MQQUEQE/src/com/message/message.txt"));
        String message = prop.getProperty("msg");
        new SimpleJMSProducer().sendMsg(message);
        System.out.println(message);

    }
}
Once message consumes,current queue depth becomes 0.

 

 

ActiveMQ Consumer and producer

 

Monday, August 27, 2018

WebSphere MQ Basic commands

IBM MQ Commands

Commands are case sensitive and lower case.

Some of the most popular sample programs are:

amqsput PUT

amqsbcg BROWSE

amqsget GET

These are some of the most common:

crtmqm – creates QMGR

strmqm – starts QMGR

endmqm – ends QMGR

dltmqm – deletes QMGR

runmqsc – starts MQ script

Create a queue manager
command:
 crtmqm QM1

Start the queue manager
 strmqm QM1

Starting MQSC for queue manager QM1.
 runmqsc QM1

Create a local queue called LQ1
 define qlocal(LQ1)

Stop the scripting tool (command line )
 end

Display Queue Manager details
DIS QMGR CONNAUTH


Displaying Queue Manager Status
 dspmq

Putting a message to the Queue LQ1
 amqsput LQ1 QM1

To end amqsput, press Enter.

Getting messages from the Queue LQ1
amqsget LQ1 QM1

Create a MQ Listener
Add Listener definition using the following commands
./runmqsc QM1
DEFINE LISTENER(QM1.listener) TRPTYPE (TCP) PORT(1414)
START LISTENER(QM1.listener)
end

Create a MQ channel

runmqsc QM1
DEFINE CHANNEL(channel_test) +
CHLTYPE(SVRCONN) +
TRPTYPE(TCP) +
DESCR(‘WebSphere MQ Default Channel’) +
REPLACE
End

****************************************
* Command: "C:\Program Files\IBM\MQ\bin\crtmqm"  -sa  QM1
****************************************

IBM MQ queue manager created.
Directory 'C:\ProgramData\IBM\MQ\qmgrs\QM1' created.
The queue manager is associated with installation 'Installation1'.
Creating or replacing default objects for queue manager 'QM1'.
Default objects statistics : 86 created. 0 replaced. 0 failed.
Completing setup.
Setup completed.
exitvalue = 0
****************************************
* Command: "C:\Program Files\IBM\MQ\bin\strmqm" QM1
****************************************

IBM MQ queue manager 'QM1' starting.
The queue manager is associated with installation 'Installation1'.
5 log records accessed on queue manager 'QM1' during the log replay phase.
Log replay for queue manager 'QM1' complete.
Transaction manager state recovered for queue manager 'QM1'.
IBM MQ queue manager 'QM1' started using V9.0.0.2.
exitvalue = 0
****************************************
* Command: "C:\Program Files\IBM\MQ\bin\runmqsc" QM1
* Input: DEFINE LISTENER('LISTENER.TCP') TRPTYPE(TCP) PORT(1414) CONTROL(QMGR)
****************************************
5724-H72 (C) Copyright IBM Corp. 1994, 2016.
Starting MQSC for queue manager QM1.
     1 : DEFINE LISTENER('LISTENER.TCP') TRPTYPE(TCP) PORT(1414) CONTROL(QMGR)
AMQ8626: IBM MQ listener created.
One MQSC command read.
No commands have a syntax error.
All valid MQSC commands were processed.
exitvalue = 0
****************************************
* Command: "C:\Program Files\IBM\MQ\bin\runmqsc" QM1
* Input: START LISTENER('LISTENER.TCP')
****************************************
5724-H72 (C) Copyright IBM Corp. 1994, 2016.
Starting MQSC for queue manager QM1.
     1 : START LISTENER('LISTENER.TCP')
AMQ8021: Request to start IBM MQ listener accepted.
One MQSC command read.
No commands have a syntax error.
All valid MQSC commands were processed.
exitvalue = 0