一.去activemq官网下载mq软件

去Apache官网下载activemq软件,并安装。

二.编写Java代码

java编程中spring boot整合activemq实现MQ的使用
1.在spring boot项目中添加activemq的依赖
<!-- activemq support -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-activemq</artifactId>
		</dependency>
<!-- /activemq support -->
2.application.properties配置文件中添加mq的相关配置
#==================activemq Config Start==================
spring.activemq.broker-url=tcp://127.0.0.1:61616
spring.activemq.in-memory=true
spring.activemq.password=admin
spring.activemq.user=admin
spring.activemq.packages.trust-all=false
spring.activemq.packages.trusted=
spring.activemq.pool.configuration.*=
spring.activemq.pool.enabled=false
spring.activemq.pool.expiry-timeout=0
spring.activemq.pool.idle-timeout=30000
spring.activemq.pool.max-connections=1
#==================activemq Config End  ==================

3.消息提供者
package com.htwl.collection.cqyth.amq;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.jms.Destination;

import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * MQ消息提供者
 * 
 * @author leftso
 *
 */
@Component
@EnableScheduling // 测试用启用任务调度
public class Provider {
	/** MQ jms实例 **/
	@Autowired
	private JmsMessagingTemplate jmsMessagingTemplate;

	private static int count = 0;

	@Scheduled(fixedDelay = 5000) // 每5s执行1次-测试使用
	public void send() {

		Destination destination = new ActiveMQQueue("TEST_QUEUE_LOG");// 这里定义了Queue的key
		String message = "Send AMQ Test ..." + count;
		System.out.println("[" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + "]" + message);
		count++;
		this.jmsMessagingTemplate.convertAndSend(destination, message);
	}
}
4.消费
package com.htwl.collection.cqyth.amq;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

@Component
public class Consumer {

	Logger LOGGER = LoggerFactory.getLogger(this.getClass());

	/**
	 * 使用@JmsListener注解来监听指定的某个队列内的消息
	 **/
	@JmsListener(destination = "TEST_QUEUE_LOG")
	public void removeMessage(String msg) {
		System.out.println("["+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())+"]Receive:"+msg);
	}
}
 
暂无评论