activemq的通信方式有如下几种:P2P、pub/sub、request-response

其中request-response是应答的模式,不是默认支持的。但可以通过JMSReplyTo和JMSCorrelationID实现。理论基础不再详述,可参考 http://shmilyaw-hotmail-com.iteye.com/blog/1897635

下面直接附上代码:


P2P

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * P2P模式
 * 生产者
 * 1、实例化连接工厂 ConnectionFactory 
 * 2、通过连接工厂获取连接并启动 Connection 
 * 3、通过连接创建会话 Session 
 * 4、通过会话创建目的地(消息队列) Destination 
 * 5、通过会话创建该消息队列的生产者 MessageProducer 
 * 6、通过会话创建消息并由生产者发送 TextMessage
 * @author 041957
 *
 */
public class JMSProducer {
    
    //默认连接用户名
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    //默认连接密码
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    //默认连接地址
    private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;

    public static void main(String[] args) {
        ConnectionFactory connectionFactory;
        Connection connection = null;
        Session session;
        Destination destination;
        MessageProducer messageProducer;
        try {
            connectionFactory = new ActiveMQConnectionFactory(JMSProducer.USERNAME, JMSProducer.PASSWORD, JMSProducer.BROKEURL);
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
            destination = session.createQueue("HelloWorld");
            messageProducer = session.createProducer(destination);
            for(int i=0; i<10; i++){
                TextMessage textMessage = session.createTextMessage("发送 activemq 消息:" + i);
                System.out.println("发送 activemq 消息:" + i);
                messageProducer.send(textMessage);
            }
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(connection!=null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    
}
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * P2P模式
 * 消费者
 * 1、实例化连接工厂 ConnectionFactory 
 * 2、通过连接工厂获取连接并启动 Connection 
 * 3、通过连接创建会话 Session 
 * 4、通过会话创建目的地(消息队列) Destination 
 * 5、通过会话创建该消息队列的消费者 MessageConsumer   
 * 6、消费者接收消息 TextMessage
 * @author 041957
 *
 */
public class JMSConsumer {
    
    //默认连接用户名
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    //默认连接密码
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    //默认连接地址
    private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;

    public static void main(String[] args) {
        ConnectionFactory connectionFactory;
        Connection connection = null;
        Session session;
        Destination destination;
        MessageConsumer messageConsumer;
        try {
            connectionFactory = new ActiveMQConnectionFactory(JMSConsumer.USERNAME, JMSConsumer.PASSWORD, JMSConsumer.BROKEURL);
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            destination = session.createQueue("HelloWorld");
            messageConsumer = session.createConsumer(destination);
            while(true){
                TextMessage textMessage = (TextMessage) messageConsumer.receive(100000);
                if(textMessage != null){
                    System.out.println("收到的消息:" + textMessage.getText());
                }else {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(connection!=null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    
}



pub/sub

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * pub/sub模式
 * 消息发布者
 * @author 041957
 *
 */
public class JMSPublisher {

    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    //默认连接密码
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    //默认连接地址
    private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;

    public static void main(String[] args) {
        ConnectionFactory connectionFactory;
        Connection connection = null;
        Session session;
        MessageProducer messageProducer;
        Destination[] destinations = new Destination[3];
        try {
            connectionFactory = new ActiveMQConnectionFactory(JMSPublisher.USERNAME, JMSPublisher.PASSWORD, JMSPublisher.BROKEURL);
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            messageProducer = session.createProducer(null);
            for(int i=0; i<destinations.length; i++){
                destinations[i] = session.createTopic("Topic_" + i);
            }
            for(int i=0; i<destinations.length; i++){
                TextMessage textMessage = session.createTextMessage("发送 topic: " + i);
                System.out.println("发送 topic: " + i);
                messageProducer.send(destinations[i], textMessage);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(connection!=null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * pub/sub模式
 * 消息订阅者
 * @author 041957
 *
 */
public class JMSSubscriber {

    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    //默认连接密码
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    //默认连接地址
    private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;

    public static void main(String[] args) {
        ConnectionFactory connectionFactory;
        Connection connection = null;
        Session session;
        try {
            connectionFactory = new ActiveMQConnectionFactory(JMSSubscriber.USERNAME, JMSSubscriber.PASSWORD, JMSSubscriber.BROKEURL);
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            for(int i=0; i<3; i++){
                Destination destination = session.createTopic("Topic_" + i);
                MessageConsumer messageConsumer = session.createConsumer(destination);
                messageConsumer.setMessageListener(new MessageListener(){
                    public void onMessage(Message message) {
                        TextMessage textMessage = (TextMessage)message;
                        try {
                            System.out.println("订阅获取了消息:" + textMessage.getText());
                        } catch (JMSException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                });
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}


request-response

import java.util.UUID;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * request-response模式
 * 应答的主要逻辑
 * 该模式不是默认提供的模式,但可以通过JMSReplyTo和JMSCorrelationID实现
 * 1、创建临时队列,并设置到消息中的JMSReplyTo,用于返回消息的发送
 * 2、创建随机ID,并设置到消息中的JMSCorrelationID,用于返回消息知道发送给哪个请求
 * 3、创建临时队列的消费者并监听
 * 4、监听处理完成后关闭连接
 * @author 041957
 *
 */
public class JMSRequest {
    
    //默认连接用户名
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    //默认连接密码
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    //默认连接地址
    private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;

    public static void main(String[] args) {
        ConnectionFactory connectionFactory;
        final Connection connection;
        Session session;
        Destination destination;
        MessageProducer messageProducer;
        TextMessage textMessage;
        try {
            connectionFactory = new ActiveMQConnectionFactory(JMSRequest.USERNAME, JMSRequest.PASSWORD, JMSRequest.BROKEURL);
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            destination = session.createQueue("HelloWorld");
            messageProducer = session.createProducer(destination);
            textMessage = session.createTextMessage("请求消息,需要回复!");
            
            Destination destTmp = session.createTemporaryQueue();
            MessageConsumer responseConsumer = session.createConsumer(destTmp);
            textMessage.setJMSReplyTo(destTmp);
            textMessage.setJMSCorrelationID(UUID.randomUUID().toString());
            responseConsumer.setMessageListener(new MessageListener(){
                public void onMessage(Message message) {
                    // TODO Auto-generated method stub
                    TextMessage textMessage = (TextMessage)message;
                    try {
                        System.out.println("request收到response回复的消息:" + textMessage.getText());
                        connection.close();
                    } catch (JMSException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            });
            messageProducer.send(textMessage);
            System.out.println("发送消息后接着做其他事情!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * request-response模式
 * 应答的主要逻辑:
 * 1、从消息中获取 JMSReplyTo和JMSCorrelationID
 * 2、将JMSCorrelationID设置到需要返回的消息中
 * 3、创建生产者并往JMSReplyTo队列发送消息
 * @author 041957
 *
 */
public class JMSResponse {
    
    //默认连接用户名
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    //默认连接密码
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    //默认连接地址
    private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;

    public static void main(String[] args) {
        ConnectionFactory connectionFactory;
        Connection connection = null;
        final Session session;
        Destination destination;
        MessageConsumer messageConsumer;
        final MessageProducer messageProducer;
        try {
            connectionFactory = new ActiveMQConnectionFactory(JMSResponse.USERNAME, JMSResponse.PASSWORD, JMSResponse.BROKEURL);
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            destination = session.createQueue("HelloWorld");
            messageConsumer = session.createConsumer(destination);
            messageProducer = session.createProducer(null);
            messageConsumer.setMessageListener(new MessageListener(){
                public void onMessage(Message message) {
                    TextMessage textMessage = (TextMessage)message;
                    try {
                        System.out.println("response收到request发送的消息:" + textMessage.getText());
                        
                        TextMessage responseMessage = session.createTextMessage("回复消息,操作成功");
                        responseMessage.setJMSCorrelationID(message.getJMSCorrelationID());
                        messageProducer.send(message.getJMSReplyTo(), responseMessage);
                    } catch (JMSException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}