activeMq之hello(java)

时间:2023-03-09 14:27:24
activeMq之hello(java)

消息队列activeMq,   节省响应时间,解决了第三方响应时间长的问题让其他客户可以继续访问,

安装activeMq

apache-activemq-5.14.0-bin\apache-activemq-5.14.0\bin\win64\activeMq.bat

创建一个maven java project

在浏览器中访问路径  http://localhost:8161/        登录名admin  密码为admin

activeMq之hello(java)

1.pom.xml文件

<dependencies>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.14.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>

  

生产任务

    public static void main(String[] args) throws JMSException {

		//连接工厂
ConnectionFactory factory = new ActiveMQConnectionFactory();
//获取一个连接
Connection connection = factory.createConnection();
//建立会话
Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
//创建队列化话题对象
Queue queue = session.createQueue("hello");
MessageProducer producer = session.createProducer(queue);
for (int i = 0; i < 10; i++) {
producer.send(session.createTextMessage("ActiveMQ"+i));
}
session.commit();
}

  产生了十条任务

activeMq之hello(java)

消费(处理业务)

public static void main(String[] args) throws Exception {
//连接工厂
ConnectionFactory factory = new ActiveMQConnectionFactory();
//获取一个连接
Connection connection = factory.createConnection();
connection.start();
//建立会话
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//创建队列化话题对象
Queue queue = session.createQueue("hello");
MessageConsumer producer = session.createConsumer(queue);
while(true){
//接收消息
TextMessage receive = (TextMessage) producer.receive();
if(receive!=null){
System.out.println(receive.getText());
}
}
}

  activeMq之hello(java)