<–start–>
使用Java程序操作ActiveMQ生产消息,代码的复杂度较高,但也没有默写下来的必要。
开发ActiveMQ首先需要导入activemq-all.jar包,如果是maven项目,就需要在pom文件中导入坐标。本例中创建的是一个maven项目,所以在pom文件中引入坐标:
1 <dependency>
2 <groupId>org.apache.activemq</groupId>
3 <artifactId>activemq-all</artifactId>
4 <version>5.14.0</version>
5 </dependency>
要测试代码就需要引入juint坐标:
1 <dependency>
2 <groupId>junit</groupId>
3 <artifactId>junit</artifactId>
4 <version>4.12</version>
5 </dependency>
Java代码操作ActiveMQ生产消息:
1 public class ActiveMQProducer {
2 @Test
3 public void testProduceMQ() throws Exception {
4 // 连接工厂
5 // 使用默认用户名、密码、路径
6 // 路径 tcp://host:61616
7 ConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
8 // 获取一个连接
9 Connection connection = connectionFactory.createConnection();
10 // 建立会话
11 Session session = connection.createSession(true,
12 Session.AUTO_ACKNOWLEDGE);
13 // 创建队列或者话题对象
14 Queue queue = session.createQueue("HelloWorld");
15 // 创建生产者 或者 消费者
16 MessageProducer producer = session.createProducer(queue);
17
18 // 发送消息
19 for (int i = 0; i < 10; i++) {
20 producer.send(session.createTextMessage("你好,activeMQ:" + i));
21 }
22 // 提交操作
23 session.commit();
24
25 }
26 }
<–end–>