码迷,mamicode.com
首页 > 其他好文 > 详细

创建Topic生产者并往ActiveMQ发送消息

时间:2020-03-09 13:40:06      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:地方   catch   rac   str   实例   ext   provider   发送   ring   

 1 import java.util.Random;        
 2 import javax.jms.Connection;
 3 import javax.jms.ConnectionFactory;
 4 import javax.jms.DeliveryMode;
 5 import javax.jms.Destination;
 6 import javax.jms.JMSException;
 7 import javax.jms.MessageProducer;
 8 import javax.jms.Session;
 9 import javax.jms.TextMessage;
10 import org.apache.activemq.ActiveMQConnectionFactory;
11 
12 public class SendMessage {  
13     private static final String url = "tcp://localhost:61616";  
14     private static final String TOPICS_NAME = "alarm";  
15 
16     public void sendMessage() throws JMSException {  
17    // JMS 客户端到JMSProvider 的连接  
18    Connection connection = null;  
19    try {  
20        // 连接工厂,JMS 用它创建连接  
21        // 构造ConnectionFactory实例对象,此处采用ActiveMq的实现jar  
22        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);  
23        connection = (Connection)connectionFactory.createConnection();  
24        // 启动连接  
25        connection.start();  
26        //Session:发送或接收消息的线程  
27        // 获取session  
28        Session session = (Session) connection.createSession(false,  
29               Session.AUTO_ACKNOWLEDGE);  
30        // 消息的目的地,消息发送到那个队列  
31        Destination destination = session.createTopic(TOPICS_NAME);  
32        //MessageProducer:消息发送者(生产者)  
33        // 创建消息发送者  
34        MessageProducer producer =session.createProducer(destination);  
35        // 设置是否持久化  
36        //DeliveryMode.NON_PERSISTENT:不持久化  
37        //DeliveryMode.PERSISTENT:持久化  
38        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);  
39 
40        String msg = "";  
41        int i = 0;  
42     do {  
43         msg = "第"+i + "次发送的消息:"+new Random();  
44             TextMessage message = session.createTextMessage(msg);  
45             Thread.sleep(1000);  
46             // 发送消息到目的地方  
47            producer.send(message);  
48             System.out.println("发送消息:" +msg);  
49             i++;  
50     } while (i<10);  
51    } catch (Exception e) {  
52        e.printStackTrace();  
53    }  
54 }  
55 
56 public static void main(String[] args) {  
57    SendMessage sndMsg = new SendMessage();  
58    try {  
59        sndMsg.sendMessage();  
60    } catch (Exception ex) {  
61        System.out.println(ex.toString());  
62    }  
63 }  
64 }

 

创建Topic生产者并往ActiveMQ发送消息

标签:地方   catch   rac   str   实例   ext   provider   发送   ring   

原文地址:https://www.cnblogs.com/lhq1996/p/12448019.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!