MQ is an old actor. This article mainly records the configuration and writing process of ActiveMQ from download to application to the project.
Let everyone quickly configure to the application
Download and modify the configuration
First, download ActiveMQ, this is the official website download address: https://activemq.apache.org/components/classic/download/
After downloading, find the activemq.xml file in the config directory
Find the <policyEntries> tag, add configuration under the tag
<!--死信队列-->
<policyEntry topic=">" >
<deadLetterStrategy>
<!--
queuePrefix:设置死信队列前缀
useQueueForQueueMessages: 设置使用队列保存死信,还可以设置useQueueForTopicMessages,使用Topic来保存死信
-->
<individualDeadLetterStrategy queuePrefix="DLQ." useQueueForQueueMessages="true" processNonPersistent="true" />
</deadLetterStrategy>
</policyEntry>
This is to configure the dead letter queue
Maven dependencies that need to be used
<!--activemq-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<!--activemq pool-->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
</dependency>
Configure SpringBoot's YML file
spring:
#ActiveMQ基础配置
activemq:
#通信地址,不是http,是tcp,61616是;连接地址
broker-url: tcp://127.0.0.1:61616
#账号密码可以在MQ的users.properties配置文件中配置
user: admin
password: admin
pool:
#是否启用
enabled: true
#最大连接数
max-connections: 100
Producer configuration use
Producer-config class
//MQ的配置
@Configuration
public class ActiveMQConfig {
//yml配置文件中的那个连接地址
@Value("${spring.activemq.broker-url}")
private String brokerUrl;
//队列的Bean
@Bean
public Queue getQueue(){
return new ActiveMQQueue("ActiveMQQueue");
}
//连接工厂的Bean,brokerUrl连接地址
@Bean
public ActiveMQConnectionFactory connectionFactory(){
return new ActiveMQConnectionFactory(brokerUrl);
}
}
Producer-use
Use @Scheduled(cron = "0/5 ?") timed task annotation, you need to add @EnableScheduling annotation to the startup class to scan
@Autowired
private JmsMessagingTemplate messagingTemplate;
@Autowired
private Queue queue;
//定时任务的注解(启动后每隔5秒执行一次)
@Scheduled(cron = "0/5 * * * * ?")
//事务注解
@Transactional(rollbackFor = Exception.class)
public void task() {
System.out.println("定时任务执行...");
//放入队列
messagingTemplate.convertAndSend(queue, "MingLog");
System.out.println("已放入队列...");
}
Consumer configuration and use
Consumer-config class
//RctiveMQ 消费者的配置
@Configuration
public class ActiveMQConfig {
//yml配置文件中的那个连接地址
@Value("${spring.activemq.broker-url}")
private String brokerUrl;
//连接工厂的Bean
@Bean
public ActiveMQConnectionFactory connectionFactory(RedeliveryPolicy redeliveryPolicy){
ActiveMQConnectionFactory activeMQConnectionFactory =
//账号、密码、连接地址
new ActiveMQConnectionFactory("admin","admin",brokerUrl);
//配置控制消息在回滚时如何重新传递
activeMQConnectionFactory.setRedeliveryPolicy(redeliveryPolicy);
return activeMQConnectionFactory;
}
//messageConsumer的配置选项Bean
@Bean
public RedeliveryPolicy getRedeliveryPolicy(){
return new RedeliveryPolicy();
}
//消息的监听连接工厂Bean
@Bean
public JmsListenerContainerFactory getJmsListenerContainerFactory(ActiveMQConnectionFactory connectionFactory){
//创建默认消息监听工厂
DefaultJmsListenerContainerFactory defaultJmsListenerContainerFactory = new DefaultJmsListenerContainerFactory();
//将连接工厂set进去
defaultJmsListenerContainerFactory.setConnectionFactory(connectionFactory);
//设置消费确认方式 1: 自动确认,2: 客户端手动确认,3:自动批量确认,4 事务提交并确认。
defaultJmsListenerContainerFactory.setSessionAcknowledgeMode(2);
return defaultJmsListenerContainerFactory;
}
}
Consumer-use
Generally use message listeners to perform tasks/methods/businesses
The message is successful, manually confirm acknowledge()
Message consumption failed, manual rollback, recover()
A single message fails to be consumed 6 times, and the message enters the dead letter queue
//消息监听注解,destination要监听的队列,containerFactory消息监听的连接工厂
@JmsListener(destination = "ActiveMQQueue", containerFactory = "jmsListenerContainerFactory")
//TextMessage 监听到的消息
public void mqListenerEvent(TextMessage textMessage, Session session) throws JMSException {
try {
String text = textMessage.getText();
System.out.println("收到的消息:" + text);
//业务代码
//消息消费确认
textMessage.acknowledge();
}catch (Exception e){
System.out.println("异常了...");
e.getMessage();
//消息回滚
session.recover();
}
}
Therefore, in general, we will maintain the dead letter queue separately, and will compensate and record logs for messages that are successfully consumed.
Dead letter queue monitoring is similar to the above monitoring, except that the monitoring object is different
//监听死信队列
@JmsListener(destination = "ActiveMQ.DLQ")
public void receive2(TextMessage textMessage, Session session) throws JMSException {
try {
//做日志记录、补偿策略、记录DB、Redis等等等等
System.out.println("死信队列:"+textMessage.getText());
//记录好,手动确认
textMessage.acknowledge();
}catch (Exception e){
System.out.println("异常了...");
e.getMessage();
//消息回滚
session.recover();
}
}
Alright, this is the end, let’s go start and try
Hey, if you like, you can follow my WeChat public account. I heard that the ones you are following now will be honorable old fans in the future.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。