首先去官网下载ActiveMQ,链接如下:
ActiveMQ官网下载地址
由于本地演示测试,所以下载的windows版本。
下载完成解压到任意盘,我在D盘解压:
进入bin目录,可以看到64位和32位2个目录:
我本地是64位,所以选择64位目录进入,双击 activemq.bat 运行,如下图所示:
运行成功,我们前往登陆页面:
http://localhost:8161/
用户名密码默认为:admin
看到如下图所示:
登陆成功。
下面演示项目实例:
1. 首先添加Maven依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
2.然后创建activeMQ链接配置文件:
#activeMQ配置
#activemqUrl
activemqUrl=tcp://127.0.0.1:61616
#activemq用户名
activemqUser=admin
#activemq密码
activemqPassword=admin
项目中activeMQ目录结构如图所示:
3. 创建ActiveMQ 配置类
package com.club.business.activemq;
import com.club.business.config.ActiveMqConfig;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.RedeliveryPolicy;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import javax.jms.ConnectionFactory;
import javax.jms.Session;
/**
* ActiveMQ 配置类
*/
@Configuration
public class ActiveMqTopicConfig {
/**
* JMS 队列的监听容器工厂
*/
public static DefaultJmsListenerContainerFactory jmsTopicListenerContainerFactory() {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory());
factory.setPubSubDomain(true);
factory.setSessionTransacted(true);
factory.setAutoStartup(true);
/**开启持久化订阅*/
factory.setSubscriptionDurable(true);
/**重连间隔时间*/
factory.setRecoveryInterval(1000L);
factory.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE);
return factory;
}
/**
* 链接工厂方法
* @return
*/
public static ConnectionFactory connectionFactory(){
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
/**此处获取的是配置文件内容*/
connectionFactory.setBrokerURL(ActiveMqConfig.ACTIVEMQ_URL);
connectionFactory.setUserName(ActiveMqConfig.ACTIVEMQ_USER);
connectionFactory.setPassword(ActiveMqConfig.ACTIVEMQ_PASSWORD);
/**设置重发属性*/
connectionFactory.setRedeliveryPolicy(redeliveryPolicy());
return connectionFactory;
}
/**
* 设置重发属性
* @return
*/
public static RedeliveryPolicy redeliveryPolicy(){
RedeliveryPolicy redeliveryPolicy= new RedeliveryPolicy();
/**是否在每次尝试重新发送失败后,增长这个等待时间*/
redeliveryPolicy.setUseExponentialBackOff(true);
/**重发次数,默认为6次,这里设置为10次,-1表示不限次数*/
redeliveryPolicy.setMaximumRedeliveries(0);
/**重发时间间隔,默认为1毫秒,设置为10000毫秒*/
redeliveryPolicy.setInitialRedeliveryDelay(10000);
/**
* 表示没有拖延只有UseExponentialBackOff(true)为true时生效
* 第一次失败后重新发送之前等待10000毫秒,第二次失败再等待10000 * 2毫秒
* 第三次翻倍10000 * 2 * 2,以此类推
*/
redeliveryPolicy.setBackOffMultiplier(2);
/**是否避免消息碰撞*/
redeliveryPolicy.setUseCollisionAvoidance(true);
/**设置重发最大拖延时间360000毫秒 表示没有拖延只有UseExponentialBackOff(true)为true时生效*/
redeliveryPolicy.setMaximumRedeliveryDelay(360000);
return redeliveryPolicy;
}
}
4.创建activeMQ - 监听配置类(监听使用的每个方法必须在此配置)
package com.club.business.activemq.topicbean;
import com.club.business.activemq.ActiveMqTopicConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
/**
* activeMQ - 监听配置类(监听时调用此地注册的Bean,每个Bean中配置工厂方法创建监听)
* 注意:每个方法创建的对象必须set一个唯一的ClientId (此Id自定义,不能冲突,可避免不同 方法调用产生阻断)
*/
@Configuration
public class TopicBean {
@Bean(name = "topicAsnListener")
public DefaultJmsListenerContainerFactory topicAsnListener(){
DefaultJmsListenerContainerFactory factory = ActiveMqTopicConfig.jmsTopicListenerContainerFactory();
factory.setClientId("vp-mid-stock-asn-98");
return factory;
}
@Bean(name = "topicSoListener")
public DefaultJmsListenerContainerFactory topicSoListener(){
DefaultJmsListenerContainerFactory factory = ActiveMqTopicConfig.jmsTopicListenerContainerFactory();
factory.setClientId("vp-mid-stock-so-98");
return factory;
}
}
5.创建生产者接口
package com.club.business.activemq.product;
import javax.jms.Destination;
/**
* activeMQ
*
* @Description 生产者接口
* @author Tom
* @date 2019-12-17
*/
public interface IProducerService {
void push(Destination destination, Object message);
void push(String destinationName, Object message);
}
6.创建生产者接口实现类:
package com.club.business.activemq.product.impl;
import com.club.business.activemq.product.IProducerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
/**
* activeMQ
*
* @Description 生产者实现类
* @author Tom
* @date 2019-12-17
*/
@Service
public class ProducerServiceImpl implements IProducerService {
@Autowired
private JmsTemplate jmsTemplate;
@Override
public void push(Destination destination, Object message) {
jmsTemplate.send(destination, new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(message.toString());
}
});
}
@Override
public void push(String destinationName, Object message) {
jmsTemplate.send(destinationName, new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
return session.createTextMessage(message.toString());
}
});
}
}
7.创建测试类 - 监听activeMQ消息
package com.club.business.activemq.service;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;
/**
* demo 监听activeMQ接收消息 测试类
*
* @author Tom
* @date 2019-12-17
*/
@Service
public class AsnOrderBackListener {
private static final Logger log = LoggerFactory.getLogger(AsnOrderBackListener.class);
/**
* 监听消息方法demo
*
* 注意:@JmsListener(destination = "asnOrderBackTopic", containerFactory = "topicAsnListener")中
* destination参数为destination字段,根据消息发送者定义的名称书写
* containerFactory参数为 监听配置类TopicBean中配置的名称,只有正确配置才能监听
* @param message 监听到消息字符串
*/
@JmsListener(destination = "asnOrderBackTopic", containerFactory = "topicAsnListener")
public void getMessage(String message) {
log.info("入库订单监听消息队列,传来的值为:{}",message);
try {
if (StringUtils.isNotBlank(message)) {
JSONObject list = JSONObject.parseObject(message);
if (list == null) {
return;
}
String msg = list.getString("msg");
System.err.println("接收到消息啦,消息内容为:" + msg);
/**处理逻辑内容*/
}
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
}
}
}
8.创建测试类 消息生产者 - 消息发送:
package com.club.business.activemq.demo;
import com.alibaba.fastjson.JSONObject;
import com.club.business.activemq.product.IProducerService;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.jms.Destination;
/**
* 发送消息测试类
*/
@Controller
@RequestMapping("/SendMqTest")
public class SendMqTest {
@Autowired
private IProducerService producerService;
/**
* 消息发送方法
* @param msg 发送内容
*/
@RequestMapping(value = "/msg")
public void sendMq(String msg){
JSONObject json = new JSONObject();
json.put("msg",msg);
try {
/**作为生产者 asnOrderBackTopic 为消息名称唯一标识,消费者根据此名接收消息*/
Destination destination = new ActiveMQQueue("asnOrderBackTopic");
producerService.push(destination, json.toString());
} catch (Exception e) {
/**
* 此处可将异常数据插入数据库或记录
*/
e.printStackTrace();
}
}
}
测试成功:
2019-12-17 15:14:55.076 INFO 11020 --- [enerContainer-1] c.c.b.a.service.AsnOrderBackListener : 入库订单监听消息队列,传来的值为:{"msg":"这是我的消息"}
接收到消息啦,消息内容为:这是我的消息