ActiveMQ简单实现
(activemq-all-5.16.0.jar)
public class MQTest { public static void main(String[] args) throws Exception { mqSendQueue(); //mqAcceptQueue(); } public static void mqSendQueue() throws JMSException { //1.创建工厂连接对象,需要指定IP和端口号 ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616"); //2.使用连接工厂创建一个对象 Connection connection = factory.createConnection(); //3.开启连接 connection.start(); //4.使用连接对象创建会话(session)对象 Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE); //5.使用会话对象创建目标对象,包括queue和topic(一对一和一对多) // Queue queue = session.createQueue("test-queue"); //一对一 Topic topic = session.createTopic("test-topic"); //一对多 //6.使用会话对象创建生产者对象 //MessageProducer producer = session.createProducer(queue); MessageProducer producer = session.createProducer(topic); //7.使用会话对象创建一个消费者对象 TextMessage message = session.createTextMessage("hello!test-topic"); //8.发送消息 producer.send(message); //9.关闭资源 producer.close(); session.close(); connection.close(); } public static void mqAcceptQueue() throws Exception { //1.创建工厂连接对象,需要制定Ip和端口号 ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://127.0.0.1:61616"); //2.使用连接工厂创建一个对象 Connection connection = factory.createConnection(); //3.开启连接 connection.start(); //4.使用连接对象创建会话(Session)对象 Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE); //5.使用会话对象创建目标对象,包含queue和topic //Queue queue = session.createQueue("test-queue"); Topic topic = session.createTopic("test-topic"); //6.使用会话对象创建生产者对象 //MessageConsumer consumer = session.createConsumer(queue); MessageConsumer consumer = session.createConsumer(topic); //7.向consumer对象种设置一个messageListener对象用来接收对象 consumer.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { if(message instanceof TextMessage){ TextMessage textMessage = (TextMessage) message; try { System.out.println(textMessage.getText()); } catch (JMSException e) { e.printStackTrace(); } } } }); //8.程序等待接收用户消息 System.in.read(); //9.关闭资源 consumer.close();; session.close(); connection.close(); }