ActiveMQ两种消息模式以及为什么使用MQ

1.为什么使用MQ

 a.高并发

在高并发分布式环境下,由于来不及同步处理,请求往往发生堵塞;通过消息队列,可以异步处理请求,缓解系统的压力;

b.松耦合性

一个应用发送消息到MQ之后并不关系消息如何或者什么时候被传递,同样的消息的接收者也不关系消息从哪里来的。在不同的环境中这样做的好处是允许客户端使用不同的语言编写甚至使用不同的线路协议,MQ作为中间人存在,允许不同环境的集成和异步交互。


2.点对点消息

package com.imooc.jms;

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;

public class JMSProducer {

    //默认连接用户名
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    //默认连接密码
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    //默认连接地址
    private static final String BROKEURL = "tcp://localhost:61618";
    //发送的消息数量
    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);
        }

    }
}

package com.imooc.jms;

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;

public class JMSConsumer {

    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;//默认连接用户名
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;//默认连接密码
    private static final String BROKEURL = "tcp://localhost:61618";//默认连接地址

    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) {
                TextMessage textMessage = (TextMessage) messageConsumer.receive(100000);
                if(textMessage != null){
                    System.out.println("收到的消息:" + textMessage.getText());
                }else {
                    break;
                }
            }


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

    }
}


3.发布者/订阅模式

package com.imooc;

import javax.jms.Connection;
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.ActiveMQConnectionFactory;

/**
 * MQ生产者
 */
public class MQ_Producer {
	
	public static final String USER_NAME = "admin";//mq用户名
	public static final String PASSWORD = "admin";//mq密码
	public static final String BROKER_URL = "tcp://localhost:61618";//mqURL
	
	private static ActiveMQConnectionFactory connectionFactory;
	
	private static Connection connection;
	
	private static Session session;
	
	private static Destination[] destinations;//目的地
	
	private static MessageProducer producer;
	
	static{
		connectionFactory = new ActiveMQConnectionFactory(
				USER_NAME, PASSWORD, BROKER_URL);
		
		try {
			connection = connectionFactory.createConnection();
			connection.start();
			session  = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
		} catch (JMSException e) {
			e.printStackTrace();
		}
		
	}
	
	public static void sendMessage(String[] stocks) throws JMSException {
		for (int i = 0; i < stocks.length; i++) {
			Message message = createStockMessage(stocks[i]);
			producer = session.createProducer(destinations[i]);
			producer.send(destinations[i],message);
			System.out.println("Sender 发送: " + message.getStringProperty("stock"));
		}
	}
	
	public static void setTopics(String[] stocks) throws JMSException {
		destinations = new Destination[stocks.length];
		for (int i = 0; i < stocks.length; i++) {
			destinations[i] = session.createTopic("STOCKS." + stocks[i]);
		}

	}
	
	
	private static Message createStockMessage(String stock) throws JMSException {
		MapMessage message = session.createMapMessage();
		message.setString("stock",stock);
		message.setDouble("price",1.00);
		message.setDouble("offer",0.01);
		message.setBoolean("up",true);
		return message;
	}
	
	
	
	
	
	public static void close() {
		if(session != null) {
			try {
				session.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
		if(connection != null) {
			try {
				connection.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	
	
	
	
}
package com.imooc;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
/**
 * MQ消费者
 */
public class MQ_Consumer {
	
	public static final String BROKER_URL = "tcp://localhost:61618";//mqURL
	
	private static ActiveMQConnectionFactory connectionFactory;
	
	private static Connection connection;
	
	private static Session session;
	
	private static MessageConsumer consumer;
	
	static {
		connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
		try {
			connection = connectionFactory.createConnection();
			connection.start();
			session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
	public static void setTopic(String stock) throws JMSException {
		Destination destination = session.createTopic("STOCKS." + stock);
		consumer = session.createConsumer(destination);
	}
	
	
	public static void setMessageListener(MessageListener listener) throws JMSException{
		consumer.setMessageListener(listener);
	}
	
	
	
	public static void close() {
		if(session != null) {
			try {
				session.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
		if(connection != null) {
			try {
				connection.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

}

public class MyListener implements MessageListener {

	@Override
	public void onMessage(Message message) {
		MapMessage map = (MapMessage) message;
		try {
			String stock = map.getString("stock");
			double price = map.getDouble("price");
			double offer = map.getDouble("offer");
			boolean up = map.getBoolean("up");
			System.out.println(stock + "---" + price + "---" + offer + "---" + up);
		} catch (JMSException e) {
			e.printStackTrace();
		}

package com.imooc;

import javax.jms.JMSException;

public class MQtestProducer {
	
	public static void main(String[] args) {
		
		String[] stocks = {"imooc1","imooc2","imooc3"};
		try {
			MQ_Producer.setTopics(stocks);
			MQ_Producer.sendMessage(stocks);
		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			MQ_Producer.close();
		}
		
	}

}

package com.imooc;

import javax.jms.JMSException;

public class MQtestConsumer {
	
	public static void main(String[] args) {
		
		try {
			MQ_Consumer.setTopic("imooc1");
			MQ_Consumer.setMessageListener(new MyListener());
			
		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			//注释掉关闭连接的代码,否则程序停止,不能保持监听
//			MQ_Consumer.close();
		}
	}

}




阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页