ActiveMQ:使用java方式发送和拉去消息

1.声明

当前内容主要用于学习和测试使用java的方式操作ActiveMQ,以此作为记录,当前内容借鉴于官方文档

2.基本的demo

1.pom依赖

<dependencies>
	<dependency>
		<groupId>org.apache.activemq</groupId>
		<artifactId>activemq-broker</artifactId>
		<version>5.16.1</version>
	</dependency>
	<dependency>
		<groupId>org.apache.activemq</groupId>
		<artifactId>activemq-client</artifactId>
		<version>5.16.1</version>
	</dependency>
	<dependency>
		<groupId>org.apache.activemq</groupId>
		<artifactId>activemq-openwire-legacy</artifactId>
		<version>5.16.1</version>
	</dependency>
	<dependency>
		<groupId>org.apache.activemq</groupId>
		<artifactId>activemq-pool</artifactId>
		<version>5.16.1</version>
	</dependency>
</dependencies>

2.基本的工具类

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
/**
 * @author hy
 * @createTime 2021-02-28 15:42:36
 * @description 主要负责打开连接,关闭连接,预处理
 * 
 */
public class ActiveMQConnectionUtils {
    
    
	private final String url;

	// "tcp://192.168.1.100:61616"
	public ActiveMQConnectionUtils(String url) {
    
    
		if (url == null) {
    
    
			throw new IllegalArgumentException("url not be null....");
		}
		this.url = url;
	}

	public static void connStart(Connection connection) throws JMSException {
    
    
		if (connection == null) {
    
    
			throw new IllegalArgumentException("connection not be null...");
		}
		connection.start();
	}

	public Connection createConnection() throws JMSException {
    
    
		// Create a ConnectionFactory
		ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
		// 创建一个连接
		Connection connection = connectionFactory.createConnection();
		connection.start();
		return connection;
	}

	public static void closeConnection(Connection conn) {
    
    
		if (conn != null) {
    
    
			try {
    
    
				conn.close();
			} catch (JMSException e) {
    
    
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static void closeSession(Session session) {
    
    
		if (session != null) {
    
    
			try {
    
    
				session.close();
			} catch (JMSException e) {
    
    
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static void close(Connection connection, Session session) {
    
    
		closeSession(session);
		closeConnection(connection);
	}
}

3.消息接口(用于处理某些共同的操作)

public interface MessageService {
    
    
	default public void prepared(Connection connection) throws JMSException {
    
    
		ActiveMQConnectionUtils.connStart(connection);
	}
	default public void after(Connection connection,Session session) {
    
    
		ActiveMQConnectionUtils.close(connection, session);
	}
}

4.抽象类

4.1.AbstractMessageReceiver消息接收器的抽象

public abstract class AbstractMessageReceiver implements MessageService, ExceptionListener {
    
    
	private Connection connection = null;
	private Session session = null;
	public AbstractMessageReceiver(Connection connection) {
    
    
		super();
		this.connection = connection;
		try {
    
    
			prepared(connection);
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		} catch (JMSException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Message receiverMsgFromQueue(String queueName) {
    
    
		Message message = null;
		try {
    
    			
			message = receiverMsgFromQueue(session, queueName);
		} catch (Exception e) {
    
    
			System.out.println("Caught: " + e);
			e.printStackTrace();
		} finally {
    
    
			after(connection, session);
			connection = null;
			session = null;
		}
		return message;
	}

	private Message receiverMsgFromQueue(Session session, String queueName) throws JMSException {
    
    
		// Create the destination (Topic or Queue)
		Destination destination = session.createQueue(queueName);

		// Create a MessageConsumer from the Session to the Topic or Queue
		MessageConsumer consumer = session.createConsumer(destination);

		// Wait for a message
		Message message = consumer.receive(1000);
		//handlerMsg(message);
		consumer.close();
		return message;
	}

}

4.2.消息发送者的抽象

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import com.hy.activemq.test.service.MessageService;

public abstract class AbstractMessageSender implements MessageService {
    
    
	private Connection connection = null;
	private Session session = null;

	public AbstractMessageSender(Connection connection) {
    
    
		super();
		this.connection = connection;		
		try {
    
    
			prepared(connection);
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		} catch (JMSException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public Session getSession() {
    
    
		return session;
	}

	public void sendMsgToQueue(Message msg, String queueName) {
    
    
		try {
    
    
			// 创建一个session并表示不启用自动应答
			// 前后都是模板
			sendMsgToQueue(session, msg, queueName);
			// 前后都是模板
		} catch (Exception e) {
    
    
			System.out.println("Caught: " + e);
			e.printStackTrace();
		} finally {
    
    
			// 关闭会话关闭连接
			after(connection, session);
			connection = null;
			session = null;
		}
	}

	private void sendMsgToQueue(Session session, Message message, String queueName) throws JMSException {
    
    
		// Create the destination (Topic or Queue)
		Destination destination = session.createQueue(queueName);

		// 创建一个消息生产者,将消息发送到目的地为Queue
		MessageProducer producer = session.createProducer(destination);
		// 表示消息不持久化DeliveryMode.NON_PERSISTENT
		producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

		// 创建发送的消息为文本消息,需要session来创建Message
		// TextMessage message = session.createTextMessage(msg);

		// 消息生产者开始推送消息
		System.out.println("Sent message: " + message + " : " + Thread.currentThread().getName());
		producer.send(message);
	}

}

5.具体实现类

import javax.jms.Connection;
import javax.jms.JMSException;

public class MessageReceiver extends AbstractMessageReceiver {
    
    

	public MessageReceiver(Connection connection) {
    
    
		super(connection);
	}

	public synchronized void onException(JMSException ex) {
    
    
		System.out.println("JMS Exception occured.  Shutting down client.error msg:" + ex.getMessage());
	}

}
import javax.jms.Connection;

public class MessageSender extends AbstractMessageSender{
    
    

	public MessageSender(Connection connection) {
    
    
		super(connection);
		// TODO Auto-generated constructor stub
	}
}

6.测试类


import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;
import com.hy.activemq.test.msg.MessageReceiver;
import com.hy.activemq.test.msg.MessageSender;
import com.hy.activemq.test.utils.ActiveMQConnectionUtils;

/**
 * @author hy
 * @createTime 2021-02-28 14:23:59
 * @description 当前内容主要用于使用java方式连接ActiveMQ并实现基本的操作
 * 
 */
public class App {
    
    
	private static final String queueName = "myQueue";
	public static void main(String[] args) throws JMSException {
    
    
		ActiveMQConnectionUtils utils=new ActiveMQConnectionUtils("tcp://192.168.1.100:61616");
		Connection connection = utils.createConnection();
		MessageSender messageSender=new MessageSender(connection);
		TextMessage message = messageSender.getSession().createTextMessage("你好来自java的消息");
		messageSender.sendMsgToQueue(message, queueName);
		
		try {
    
    
			Thread.sleep(2000);
		} catch (InterruptedException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// 这里的客户端需要再次打开连接
		Connection connection2 = utils.createConnection();
		// 创建消息接收者,接收消息
		MessageReceiver messageReceiver=new MessageReceiver(connection2);
		Message recieveMsg = messageReceiver.receiverMsgFromQueue(queueName);
		
		// 实际获取消息
		if (recieveMsg instanceof TextMessage) {
    
    
			TextMessage textMessage = (TextMessage) recieveMsg;
			String text = textMessage.getText();
			System.out.println("Received: " + text);
		} else {
    
    
			System.out.println("Received: " + message);
		}
	}

}

3.测试结果

在这里插入图片描述
测试操作成功!

猜你喜欢

转载自blog.csdn.net/weixin_45492007/article/details/114226149