ActiveMQ学习笔记备忘一P2P模型

3 篇文章 0 订阅

ActiveMQ的P2P(点对点模式):

MQ通信模式主要有P2P和发布/订阅模型。理论及相关定义理解,只能自己去问“度娘”了,有很多很好地讲解.....                   


一、MQ相关对象关系及创建流程

1. 获得JMS connection factory. 通过我们提供特定环境的连接信息来构造factory。

2. 利用factory构造JMS connection

3. 启动connection

4. 通过connection创建JMS session.

5. 指定JMS destination.

6. 创建JMS producer或者创建JMS message并提供destination.

7. 创建JMS consumer或注册JMS message listener.

8. 发送和接收JMS message.

9. 关闭所有JMS资源,包括connection, session, producer, consumer等。


二、直接撸代码


1、消费者


package com.mq.p2p;

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;

/**
 * P2p模式-点对点 -消费者
 * @author Vivi
 */
public class Receiver implements MessageListener{
	
	//ConnectionFactory :连接工厂,JMS 用它创建连接
	private static ConnectionFactory connectionFactory;
	// Connection :JMS 客户端到JMS Provider 的连接
	private static Connection connection = null;
    // Session: 一个发送或接收消息的线程
    private static Session session;
    // Destination :消息的目的地;消息发送给谁.
    private static Destination destination;
    private static MessageConsumer consumer;
    
    public void receive() throws Exception{
    	
    	 try {
     		//第一步,獲取连接工厂
         	connectionFactory=new ActiveMQConnectionFactory(
         			ActiveMQConnection.DEFAULT_USER, 
         			ActiveMQConnection.DEFAULT_PASSWORD,
         			"tcp://localhost:61616");
         	//第二步 获取connection
 			connection =connectionFactory.createConnection();
 			//第三步,启动
 			connection.start();
 			//第四步,获取session,拿到操作连接,(是否支持事务)  
 			session = connection.createSession(true,Session.AUTO_ACKNOWLEDGE);
 			//第五步  创建一个消息目标
 			destination = session.createQueue("FirstMyQueue");
 			//第六步 
            consumer = session.createConsumer(destination);
             
            //第七步,设置监听
//            consumer.setMessageListener(this);
            
            //此处也可以用 consumer.receive(time),不用实现MessageListener
            while (true) {
                //设置接收者接收消息的时间
                TextMessage message = (TextMessage) consumer.receive(10000);
                if (null != message) {
                    System.out.println("接收到消息:" + message.getText());
                } else {
                    break;
                }
            }
             
 		} catch (JMSException e) {
 			e.printStackTrace();
 		}finally {
 			try {
                if (null != connection)
                    connection.close();
            } catch (Throwable ignore) {
            }
		}

    }
   
	@Override
	public void onMessage(Message message) {
		 //如果消息是TextMessage  
        if (message instanceof TextMessage) {  
            //强制转换一下  
            TextMessage txtMsg = (TextMessage) message;  
            try {  
                //输出接收到的消息  
                System.out.println("接收到消息 " + txtMsg.getText());  
            } catch (JMSException e) {  
                e.printStackTrace();  
            }  
        }  
	}
    public static void main(String[] args) throws Exception {
		new Receiver().receive();
	}
}

2、生成者部分



package com.mq.p2p;

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

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

public class Sender {
	 // ConnectionFactory :连接工厂,JMS 用它创建连接  
   private static ConnectionFactory connectionFactory; 
   // Connection :JMS 客户端到JMS  
   private static Connection connection = null; 
    // Session: 一个发送或接收消息的线程  
   private static Session session; 
    // Destination :消息的目的地;消息发送给谁.  
   private static Destination destination; 
    // MessageProducer:消息发送者  
   private static MessageProducer producer;
   
   
   public void producerSendMessage(){
	   // 构造ConnectionFactory实例对象
	   connectionFactory= new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, 
			   ActiveMQConnection.DEFAULT_PASSWORD, "tcp://localhost:61616");
	    try { // 构造从工厂得到连接对象  
	        connection = connectionFactory.createConnection();  
	        // 启动  
	        connection.start();  
	        // 获取操作连接  ,并开启事物
	        session = connection.createSession(Boolean.TRUE,  
	                Session.AUTO_ACKNOWLEDGE);  
	        destination = session.createQueue("FirstMyQueue");  
	        // 得到消息生成者
	        producer = session.createProducer(destination);  
	        // 设置不持久化
	        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);  
	        
	        //测试方式一
//	        TextMessage message = session.createTextMessage("Hello MQ ! I am vivid");  
//	        producer.send(message);
	        //测试方式二
	        sendMessage(session, producer);  
	        session.commit();  
	    } catch (Exception e) {  
	        e.printStackTrace();  
	    } finally {  
	        try {  
	            if (null != connection)  
	                connection.close();  
	        } catch (Throwable ignore) {  
	        }  
	    }  
   }
   
   public static void sendMessage(Session session, MessageProducer producer)  
           throws Exception {  
       for (int i = 1; i <= 10; i++) {  
           TextMessage message = session.createTextMessage("Hello MQ , I am vivid.this is my "  
                   + i+"th visited !");  
           // 发送消息到目的地方  
           System.out.println("发送消息:" + "MQ发送的消息" + i);  
           producer.send(message);  
       }  
   }  
   
   public static void main(String[] args) {
	new Sender().producerSendMessage();
}
}

3、测试相关


前提:系统安装lactiveMQ的服务,进入到bin目录启动服务,双击acticeMq.bat,ok完事!!!


启动后,进入activeMQ后台,地址:http://localhost:8161/admin/queues.jsp





启动生产者,控制台打印结果:


启动消费者,消费消息,控制台打印:






从上面的代码中可以看到生产者和消费者的代码重复度很高,我们可以对其进行简单的封装,提高对代码的利用,在实际项目更有效的进行开发



修改后的生产者:


package com.mq.p2p;

import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.TextMessage;

public class Sender2 {
    // MessageProducer:消息发送者  
   private static MessageProducer producer;
   
   
   public void producerSendMessage() throws JMSException{
	        
	   producer=(MessageProducer) ConnUtils.getConn("FirstMyQueue", ConnUtils.CREATE_TYPE_PRODUCER, null, null, null); 
	   
	   for (int i = 1; i <= 10; i++) {  
           TextMessage message = ConnUtils.getSession().createTextMessage("Hello MQ , I am vivid.this is my "  
                   + i+"th visited !");  
           // 发送消息到目的地方  
           System.out.println("发送消息:" + "MQ发送的消息" + i);  
           producer.send(message);  
       }  
   }
   
   public static void main(String[] args) throws JMSException {
	new Sender2().producerSendMessage();
}
}



修改后的消费者:


package com.mq.p2p;

import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.TextMessage;

/**
 * P2p模式-点对点 -消费者
 * @author Vivi
 */
public class Receiver2{
	
    private static MessageConsumer consumer;
    
    public void receive() throws Exception{
    	
    	 try {
    		 consumer= (MessageConsumer) ConnUtils.getConn("FirstMyQueue", ConnUtils.CREATE_TYPE_CONSUMER, null, null, null);
            //第七步,设置监听
//            consumer.setMessageListener(this);
            
            //此处也可以用 consumer.receive(time),不用实现MessageListener
            while (true) {
                //设置接收者接收消息的时间
                TextMessage message = (TextMessage) consumer.receive(10000);
                if (null != message) {
                    System.out.println("接收到消息:" + message.getText());
                } else {
                    break;
                }
            }
             
 		} catch (JMSException e) {
 			e.printStackTrace();
 		}finally {
				ConnUtils.connection_Close();
				ConnUtils.session_Close();
		}
	}
    public static void main(String[] args) throws Exception {
		new Receiver2().receive();
	}
}


封装类(这只是对其进行很简单的封装,考虑不多,只是进行学习使用):


package com.mq.p2p;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
/**
 * MQ连接及
 * @author Vivi
 *
 */
public  class ConnUtils {

		//ConnectionFactory :连接工厂,JMS 用它创建连接
		private static ConnectionFactory connectionFactory;
		// Connection :JMS 客户端到JMS Provider 的连接
		private static Connection connection = null;
	    // Session: 一个发送或接收消息的线程
	    private static Session session;
	    // Destination :消息的目的地;消息发送给谁.
	    private static Destination destination;
	    private static MessageConsumer consumer;
	    private static MessageProducer producer;
	    public final static long CREATE_TYPE_CONSUMER=1L; //消费者
	    public final static long CREATE_TYPE_PRODUCER=2L;//生产者
	    /**
	     * 
	     * @param QueueName 队列名
	     * @param type 生产者还是消费者
	     * @param user 用户名
	     * @param pass 密码
	     * @param Addr 连接MQ地址
	     * @return
	     * @throws JMSException
	     */
	    public static Object getConn(String QueueName,long type,String user,String pass,String addr) throws JMSException{
	    	
	    	//沒有給用戶名及密碼等信息為默認
	    	if((user==null||user.trim().equals(""))&&
	    			(pass==null||pass.trim().equals(""))&&(addr==null||addr.trim().equals(""))){
	    		//第一步,獲取连接工厂
	         	connectionFactory=new ActiveMQConnectionFactory(
	         			ActiveMQConnection.DEFAULT_USER, 
	         			ActiveMQConnection.DEFAULT_PASSWORD,
	         			"tcp://localhost:61616");
	    	}else{
	    		//第一步,獲取连接工厂
	         	connectionFactory=new ActiveMQConnectionFactory(user,pass,addr);
	    	}
	    	
         	//第二步 获取connection
 			connection =connectionFactory.createConnection();
 			//第三步,启动
 			connection.start();
 			//第四步,获取session,拿到操作连接,(是否支持事务)  
 			session = connection.createSession(true,Session.AUTO_ACKNOWLEDGE);
 			//第五步  创建一个消息目标
 			destination = session.createQueue(QueueName);
 			if(type==CREATE_TYPE_CONSUMER){
 				consumer=session.createConsumer(destination);
 				return consumer;
 			}else if(type==CREATE_TYPE_PRODUCER){
 				// 得到消息生成者(sender)
 	            producer = session.createProducer(destination); 
// 	           static final int NON_PERSISTENT = 1;//不持久化:服务器重启之后,消息销毁 
//             static final int PERSISTENT = 2;//持久化:服务器重启之后,消息仍存在 
 	            //持久化
 	            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
 	            return producer;
 			}else{
 				return null;
 			}
	    }
	    /**
	     * 获取session
	     * @return
	     */
	    public static Session getSession(){
	    	if(session==null){
	    		return null;
	    	}
	    	return session;
	    }
	    
	    
	    public static void connection_Close() throws JMSException{
	    	if(connection!=null){
	    		connection.close();
	    	}
	    }
	    public static void session_Close() throws JMSException{
	    	if(session!=null){
	    		session.close();
	    	}
	    	
	    }
}



代码下载地址:csdn地址:http://download.csdn.net/detail/erris/9795505

GitHub地址: https://github.com/harric/activeMQ_p2p


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值