SSM+ActiveMQ消息重发机制和消息确认机制Ack

背景:换了家新公司,接了个ssm架构的老项目,用的mq是ActiveMQ。看代码发现ActiveMQ处理消息时并没看到重试和消息确认操作,以前用的都是RabbitMQ和RocketMQ,本以为ActiveMQ没有消息重发和ACK机制,查阅资料发现还是有的,查阅资料把这个老项目的接口补上,在此记录下。

学习新东西第一原则,看官方文档。

消息重发和ACK机制官方文档地址:

http://activemq.apache.org/message-redelivery-and-dlq-handling.html

http://activemq.apache.org/redelivery-policy

应用场景:

在实际生产场景过程中,当消费者消费消息时,可能由于种种原因,导致消费者消费消息失败。例如:在一个通知系统中,生产者将通知Message
放入队列中,而消费者从队列中将消息读取出来之后,除了进行自身业务处理,还需要调用第三方服务发送短信通知用户,但在发送短信服务的时候,由于网络超时等原有导致消费失败。在这种异常情况下,希望可以建立一种机制。当未发送成功的消息,能够重新发送。处理超过一定次数后还处理不成功的,放弃处理该消息,记录下来。继续对别的消息进行处理。

代码:

mq配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:cache="http://www.springframework.org/schema/cache"
	xmlns:amq="http://activemq.apache.org/schema/core"
	xmlns:jms="http://www.springframework.org/schema/jms"
       xsi:schemaLocation="
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/jdbc
    http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
    http://www.springframework.org/schema/cache
    http://www.springframework.org/schema/cache/spring-cache.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util.xsd
	    http://www.springframework.org/schema/jms
	    http://www.springframework.org/schema/jms/spring-jms-4.0.xsd
	 	http://activemq.apache.org/schema/core
	    http://activemq.apache.org/schema/core/activemq-core-5.14.0.xsd">

    <amq:connectionFactory id="amqConnectionFactory"
                           brokerURL="tcp://127.0.0.1:61616?tcpNoDelay=true" userName="admin" password="admin"  >
        <!-- 暂时关闭安全检查,选择相信所有的包 -->
        <property name="trustAllPackages" value="true"/>
        <property name="useAsyncSend" value="true"/>
        <property name="redeliveryPolicy" ref="activeMQRedeliveryPolicy" />  <!-- 引用重发机制 -->
      </amq:connectionFactory>

    <bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
    	<!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->
        <property name="targetConnectionFactory" ref="amqConnectionFactory"/>
        <property name="reconnectOnException" value="true"/>
		<property name="cacheConsumers" value="false"/>
		<property name="cacheProducers" value="false"/>
		<!-- Session缓存数量 -->
        <property name="sessionCacheSize" value="100" />
    </bean>

    <bean id="activeMQRedeliveryPolicy" class="org.apache.activemq.RedeliveryPolicy">
        <!--是否在每次尝试重新发送失败后,增长这个等待时间-->
        <property name="useExponentialBackOff" value="true"></property>
        <!--重发次数,默认为6次-->
        <property name="maximumRedeliveries" value="5"></property>
        <!--重发时间间隔,默认为1秒-->
        <property name="initialRedeliveryDelay" value="1000"></property>
        <!--第一次失败后重新发送之前等待500毫秒,第二次失败再等待500 * 2毫秒,这里的2就是value-->
        <property name="backOffMultiplier" value="2"></property>
        <!--最大传送延迟,只在useExponentialBackOff为true时有效(V5.5),假设首次重连间隔为10ms,倍数为2,那么第 二次重连时间间隔为 20ms,第三次重连时间间隔为40ms,当重连时间间隔大的最大重连时间间隔时,以后每次重连时间间隔都为最大重连时间间隔。-->
        <property name="maximumRedeliveryDelay" value="1000"></property>
    </bean>

    <!-- Spring JmsTemplate 的消息生产者 start-->
    <!-- 定义JmsTemplate的Queue类型 -->
    <bean id="jmsQueueTemplate" class="org.springframework.jms.core.JmsTemplate">
        <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->
        <constructor-arg ref="connectionFactory" />
        <!-- 使 deliveryMode, priority, timeToLive设置生效-->
		<property name="explicitQosEnabled" value="true"/>
		<!-- 设置NON_PERSISTENT模式, 默认为PERSISTENT -->
		<property name="deliveryPersistent" value="true"/>
		<!-- 设置优先级0-9, 默认为4 -->
		<property name="priority" value="9"/>
        <!-- 非pub/sub模型(发布/订阅),即队列模式 -->
        <property name="pubSubDomain" value="false" />
        <!-- 10s -->
        <property name="receiveTimeout" value="5000" />
    </bean>

    <!-- 声明ActiveMQ消息目标,目标可以是一个队列,也可以是一个主题ActiveMQTopic -->
    <bean id="destinationOne" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg index="0" value="newCRM.mq.test"></constructor-arg>
    </bean>

    <!-- 消息监听容器 消息接收监听器用于异步接收消息 -->
    <bean id="jmsContainerOne" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="destination" ref="destinationOne" />
        <property name="messageListener" ref="mqTestMessage" />
        <property name="sessionAcknowledgeMode" value="4"></property>
    </bean>

    <!-- 定义JmsTemplate的Topic类型 -->
	<bean id="jmsTopicTemplate" class="org.springframework.jms.core.JmsTemplate">
		<!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->
		<constructor-arg ref="connectionFactory" />
		<!-- pub/sub模型(发布/订阅) -->
		<property name="pubSubDomain" value="false" />
	</bean>
</beans>

生产者(直接写的接口,没用JUnit

/**
 * @Classname TestController
 * @Description TODO
 * @Date 2020/10/19 15:10
 * @Created by will
 */
@Controller
@RequestMapping("/test")
public class TestController {

    @Resource
    private QueueSender queueSender;

    @ResponseBody
    @RequestMapping(value="/test",method= RequestMethod.GET)
    public String test(String con, HttpSession session){
        if(con==null){
            return "no";
        }
        queueSender.send("newCRM.mq.test",con);
        return "ok";
    }

}

消费者

特别注意

session.recover();不能省略,重发信息使用,注释掉之后不会重发消息,不会从队列移除,也不会进入死信队列
textMessage.acknowledge();确认消息消费成功
/**
 * @Description 队列消息监听器
 * @Date 2020/10/21 11:57
 * @Created by will
 */
@Component
public class MqTestMessage implements SessionAwareMessageListener {

	private static final Logger logger =  LoggerFactory.getLogger(MqTestMessage.class.getName());


	@Override
	public void onMessage(Message message, Session session) throws JMSException {
		if(message instanceof TextMessage){

			System.out.println("--------------------start------------------------");
			TextMessage textMessage = (TextMessage) message;
			try {
				if ("重发机制".equals(textMessage.getText())) {
					System.out.println("----------------");
					throw new RuntimeException("故意抛出的异常");
				}
				System.out.println(textMessage.getText());
				//消息确认
				textMessage.acknowledge();
				System.out.println("--------------------end------------------------");
			} catch (Exception e) {
				//重发信息使用,注释掉之后不会重发消息,不会从队列移除,也不会进入死信队列
				session.recover();
				System.out.println("我抛异常了哦");
			}
		}

	}
}

正常运行情况

触发重试机制时重试机制

消息最终也进入了MQ的死信队列

activemq入门建议看下这篇文章:https://blog.csdn.net/u012151597/article/details/78904171

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是SSM(Spring+SpringMVC+MyBatis)集成jQuery实现消息功能的代码示例: 首先是前端页面代码,使用jQuery实现消息发送和接收: ```html <!-- 发送消息 --> <div> <input type="text" id="msg" placeholder="请输入消息内容"> <button id="send-btn">发送</button> </div> <!-- 接收消息 --> <div id="msg-box"></div> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function() { // 发送消息 $("#send-btn").click(function() { var msg = $("#msg").val(); $.ajax({ url: "/sendMsg", type: "post", data: {msg: msg}, success: function(result) { console.log(result); }, error: function() { console.log("发送消息失败"); } }); }); // 接收消息 setInterval(function() { $.ajax({ url: "/getMsg", type: "get", success: function(result) { console.log(result); $("#msg-box").append("<p>" + result + "</p>"); }, error: function() { console.log("获取消息失败"); } }); }, 2000); }); </script> ``` 接下来是后端代码实现: 1. 定义消息实体类: ```java public class Message { private Integer id; private String content; private Date createTime; // getter和setter省略 } ``` 2. 定义消息DAO接口和Mapper文件: ```java public interface MessageMapper { void addMessage(Message message); List<Message> getAllMessages(); } ``` ```xml <mapper namespace="com.example.dao.MessageMapper"> <insert id="addMessage" parameterType="com.example.entity.Message"> insert into message(content, create_time) values(#{content}, now()) </insert> <select id="getAllMessages" resultMap="messageResultMap"> select * from message order by create_time desc </select> <resultMap id="messageResultMap" type="com.example.entity.Message"> <id column="id" property="id"/> <result column="content" property="content"/> <result column="create_time" property="createTime"/> </resultMap> </mapper> ``` 3. 定义消息Service接口和实现: ```java public interface MessageService { void sendMessage(String content); List<String> getAllMessages(); } @Service public class MessageServiceImpl implements MessageService { @Autowired private MessageMapper messageMapper; @Override public void sendMessage(String content) { Message message = new Message(); message.setContent(content); messageMapper.addMessage(message); } @Override public List<String> getAllMessages() { List<Message> messages = messageMapper.getAllMessages(); List<String> contents = new ArrayList<>(); for (Message message : messages) { contents.add(message.getContent()); } return contents; } } ``` 4. 定义Controller处理消息发送和接收请求: ```java @Controller public class MessageController { @Autowired private MessageService messageService; @RequestMapping("/sendMsg") @ResponseBody public String sendMsg(String msg) { messageService.sendMessage(msg); return "success"; } @RequestMapping("/getMsg") @ResponseBody public String getMsg() { List<String> messages = messageService.getAllMessages(); if (messages.size() > 0) { return messages.get(0); } else { return ""; } } } ``` 以上代码就是SSM+jQuery实现消息功能的示例,可以根据实际需求进行修改和扩展。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值