JMS学习笔记 (三)ActiveMQ简单例子

我们使用的是ActiveMQ 5.10.1 Release的Windows版,开发时候,要将apache-activemq-5.10.0-bin.zip解压缩后里面的activemq-all-5.10.0.jar包加入到classpath下面,这个包包含了所有jms接口api的实现。

JMS API中约定了Client端可以使用四种ACK_MODE,在javax.jms.Session接口中:

AUTO_ACKNOWLEDGE = 1    自动确认
CLIENT_ACKNOWLEDGE = 2    客户端手动确认  
DUPS_OK_ACKNOWLEDGE = 3    自动批量确认
SESSION_TRANSACTED = 0    事务提交并确认

可以发送的消息类型有ObjectMessage、TextMessage、MapMessage

(一)点对点的消息模型,只需要一个消息生成者和消息消费者,下面是代码。

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 javax.jms.ObjectMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
/**
 * 消息的生产者(发送者) 
 * 
 *
 */
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;
    //发送的消息数量
    private static final int SENDNUM = 10;

    public static void main(String[] args) {
        //连接工厂
        ConnectionFactory connectionFactory;
        //连接
        Connection connection = null;
        //会话 接受或者发送消息的线程
        Session session;
        //消息的目的地
        Destination destination;
        //消息生产者
        MessageProducer messageProducer;
        //实例化连接工厂
        connectionFactory = new ActiveMQConnectionFactory(JMSProducer.USERNAME, JMSProducer.PASSWORD, JMSProducer.BROKEURL);

        try {
            //通过连接工厂获取连接
            connection = connectionFactory.createConnection();
            //启动连接
            connection.start();
            //创建session
            session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
            //创建一个名称为HelloWorld的消息队列
            destination = session.createQueue("HelloWorld");
            //创建消息生产者
            messageProducer = session.createProducer(destination);
           
            
            //发送消息
            sendMessage(session, messageProducer);

            session.commit();

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(connection != null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    /**
     * 发送消息
     * @param session
     * @param messageProducer  消息生产者
     * @throws Exception
     */
    public static void sendMessage(Session session,MessageProducer messageProducer) throws Exception{
        for (int i = 0; i < JMSProducer.SENDNUM; i++) {
            //创建一条文本消息 
            TextMessage message = session.createTextMessage("ActiveMQ 发送消息" +i);
            System.out.println("发送消息:Activemq 发送消息" + i);
            //通过消息生产者发出消息 
            messageProducer.send(message);
        }

    }
}


编写消费者

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 javax.jms.ObjectMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
/**
 * 消息的消费者(接受者)
 * 
 *
 */
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;//默认连接地址,tcp://localhost:61616

    public static void main(String[] args) {
        ConnectionFactory connectionFactory;//连接工厂
        Connection connection = null;//连接

        Session session;//会话 接受或者发送消息的线程
        Destination destination;//消息的目的地

        MessageConsumer messageConsumer;//消息的消费者

        //实例化连接工厂
        connectionFactory = new ActiveMQConnectionFactory(JMSConsumer.USERNAME, JMSConsumer.PASSWORD, JMSConsumer.BROKEURL);

        try {
            //通过连接工厂获取连接
            connection = connectionFactory.createConnection();
            //启动连接
            connection.start();
            //创建session
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            //创建一个连接HelloWorld的消息队列
            destination = session.createQueue("HelloWorld");
            //创建消息消费者
            messageConsumer = session.createConsumer(destination);

            while (true) {
            	
            	//设置接收者接收消息的时间,超过时间不接收将执行下一步,如不设置此参数是长时间处于阻塞状态不执行下一步操作等到有消息才执行下一步,为了便于测试,这里谁定为500s
                TextMessage textMessage = (TextMessage) messageConsumer.receive(50000);
                if(textMessage != null){
                    System.out.println("收到的消息:" + textMessage.getText());
                }else {
                	connection.close();
                    break;
                }
                
                
            	
            }
System.out.println("消息执收完成!");

        } catch (JMSException e) {
            e.printStackTrace();
        }

    }
}


运行

首先,启动ActiveMQ,后在浏览器中输入:http://localhost:8161/admin/,然后开始执行:
运行发送者,myeclipse控制台输出,如下图:



此时,我们先看一下ActiveMQ服务器,Queues内容如下:




我们可以看到创建了一个名称为HelloWorld的消息队列,队列中有10条消息未被消费,我们也可以通过Browse查看是哪些消息,如下图:




(二)消息的发布订阅模式

编写消息发布对象

import java.util.Random;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;

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

public class Publisher {

	//默认连接用户名
    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;
    
    
   //连接工厂
    ConnectionFactory connectionFactory;
    //连接
    Connection connection = null;
    //会话 接受或者发送消息的线程
    Session session;
   //消息生产者
    MessageProducer messageProducer;
    //消息的目的地
    Destination []destinations;
    
    public Publisher() throws JMSException {  
    	//实例化连接工厂
        connectionFactory = new ActiveMQConnectionFactory(Publisher.USERNAME, Publisher.PASSWORD, Publisher.BROKEURL);
       //通过连接工厂获取连接
        connection = connectionFactory.createConnection();
        try {  
        connection.start();  
        } catch (JMSException jmse) {  
            connection.close();  
            throw jmse;  
        }  
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ;  
        messageProducer = session.createProducer(null);  
    }  
    protected void setTopics(String[] topics) throws JMSException {
    	destinations = new Destination[topics.length];
    	for(int i = 0; i < topics.length; i++) {
    		destinations[i] = session.createTopic("TOPICS." + topics[i]);
    	}
    }
    
    protected Message createMessage(String msg,int age, Session session) throws JMSException {  
        MapMessage message = session.createMapMessage();  
        message.setString("name", msg);  
        message.setInt("age", age);      
        return message;  
    }  
    
    protected void sendMessage(String msg,int age) throws JMSException {  
        for(int i = 0; i < destinations.length; i++) {  
            Message message = createMessage(msg,age, session);  
            System.out.println("发送: " + ((ActiveMQMapMessage)message).getContentMap() + " 到目标: " + destinations[i]);  
            messageProducer.send(destinations[i], message);  
        }  
    }  
    
    public void close() throws JMSException {  
        if (connection != null) {  
            connection.close();  
         }  
        
    }  
    
    public static void main(String[] args) throws JMSException {
    	
            // 创建发布消息对象	
            Publisher publisher = new Publisher();
            
            // 设置订阅者
            String []strs=new String[]{"订阅者01","订阅者02","订阅者03","订阅者04"};
            
    	    publisher.setTopics(strs);
    	    
    	    Random generator = new Random();
            for(int i=0;i<2;i++){
            	//设置要发送的消息
    		publisher.sendMessage("美男"+i,generator.nextInt(90));
    		
    		try {
    			Thread.sleep(1000);//每发一条信息暂停1秒,这个可有可无,是为了显示效果有停顿的感觉
    		} catch(InterruptedException e) {
    			e.printStackTrace();
    		}
            }
            
        // 关闭链接
        publisher.close();
    }
}


编写消息订阅对象(接收者)

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

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

public class Consumer implements MessageListener{
	//默认连接用户名
    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;
    
  //连接工厂
    ConnectionFactory connectionFactory;
    //连接
    Connection connection = null;
    //会话 接受或者发送消息的线程
    Session session;
    
    MessageConsumer messageConsumer;
    
    public Consumer(String topic) throws JMSException
    {
    	//实例化连接工厂
		  connectionFactory = new ActiveMQConnectionFactory(Consumer.USERNAME, Consumer.PASSWORD, Consumer.BROKEURL);
       //通过连接工厂获取连接
		 connection = connectionFactory.createConnection();
         connection.start();
         session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
         Destination destination = session.createTopic("TOPICS." + topic);
		 messageConsumer = session.createConsumer(destination);
		 
    }

    
    public MessageConsumer getMessageConsumer()
    {
    	return messageConsumer;
    }
	
	public static void main(String[] args) throws JMSException {
		
	    String []topics=new String[]{"订阅者01","订阅者02","订阅者03","订阅者04"};
	    for (String topic : topics) {
	    	 Consumer consumer = new Consumer(topic);
	    	 MessageConsumer messageConsumer=consumer.getMessageConsumer();
	    	 messageConsumer.setMessageListener(consumer);
	    }
	}
		
	
	@Override
	public void onMessage(Message msg) {
		// TODO Auto-generated method stub
		try {  
            MapMessage map = (MapMessage)msg;  
            String name = map.getString("name");  
            int age = map.getInt("age");    
            System.out.println(name+" 年龄:"+age+"\n");  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
	}
	
	
}



先运行订阅者对象,因为在发布/订阅的消息模型下,只有订阅者在启动或者侦听状态下才能发送成功。myeclispe如下图显示







此时,我们先看一下ActiveMQ服务器,Topic内容如下:




猜你喜欢

转载自lqllinda01.iteye.com/blog/2292994