spring mvc rocketMq简单配置

来源:互联网 发布:网络cry是什么意思啊 编辑:程序博客网 时间:2024/05/20 09:27

1.新建spring-mq-tcp.xml,并加入web.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">   <bean id="tcpMsgProducer" class="com.mq.tcp.WithdrawMsgProducer" init-method="init" destroy-method="destroy">       </bean>        <bean id="tcpMsgConsumer" class="com.mq.tcp.WithdrawMsgConsumer" init-method="init" destroy-method="destroy" >      </bean>        <bean id="msgListener" class="com.mq.tcp.WithdrawMessageListener"/> <!--Listener配置--></beans>
加入web.cml

<context-param>  <param-name>contextConfigLocation</param-name>  <param-value>classpath:spring.xml,classpath:spring-mybatis.xml,classpath:spring-redis.xml,classpath:spring-mq-tcp.xml</param-value></context-param>
2.pom.xml

<!-- RocketMQ --><dependency>    <groupId>com.alibaba.rocketmq</groupId>    <artifactId>rocketmq-all</artifactId>    <version>3.2.6</version>    <type>pom</type></dependency><dependency>    <groupId>com.alibaba.rocketmq</groupId>    <artifactId>rocketmq-client</artifactId>    <version>3.2.6</version></dependency>



3.常量参数

package com.util;/** * 〈常量类〉<br>  * @author even * @since V1.0.0 */public class CommonConstants {      public static final String MQ_PID = "xx";   public static final String MQ_CID = "xxxx";   public static final String MQ_AccessKey="xxxx";   public static final String MQ_SecretKey="XXX";   public static final String MQ_ONSAddr="XXX";   public static final String MQ_AUTO_TOPIC = "XXXX";   public static final String MQ_AUTO_TAG = "xxx";   }

4.新建监听

package com.mq.tcp;import com.aliyun.openservices.ons.api.Action;import com.aliyun.openservices.ons.api.ConsumeContext;import com.aliyun.openservices.ons.api.Message;import com.aliyun.openservices.ons.api.MessageListener;import com.service.intf.RongOrderFeedbackService;import com.service.intf.RongRepayPlanService;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;public class WithdrawMessageListener implements MessageListener {   private static final Logger log = LoggerFactory.getLogger(WithdrawMessageListener.class);   @Autowired   private RongOrderFeedbackService rongOrderFeedbackService;   @Autowired   private RongRepayPlanService rongRepayPlanService;   @Override   public Action consume(Message msg, ConsumeContext context) {      System.out.println("Receive: " + msg);      String body = "";      try {         body = new String(msg.getBody(), "UTF-8");       //这里传入body参数进行业务操作
System.out.println(body);
return Action.CommitMessage; } catch (Exception e) { log.error("消费订单号为:" + body + "的消息失败,错误详情为:" + e); int delay = msg.getReconsumeTimes(); if (delay > 4) {// 重试次数超过3次丢弃此条消息 log.warn("消费消息重试次数过多,不再消费:" + body); return Action.CommitMessage; } // 消费失败 return Action.ReconsumeLater; } } }
5.新建生产者
package com.mq.tcp;import com.aliyun.openservices.ons.api.*;import com.util.CommonConstants;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.util.Properties;public class WithdrawMsgProducer {   private final Logger logger = LoggerFactory.getLogger(WithdrawMsgProducer.class);   private Producer producer;    public void init() {          Properties producerProperties = new Properties();       producerProperties.setProperty(PropertyKeyConst.ProducerId, CommonConstants.MQ_PID);       producerProperties.setProperty(PropertyKeyConst.AccessKey, CommonConstants.MQ_AccessKey);       producerProperties.setProperty(PropertyKeyConst.SecretKey, CommonConstants.MQ_SecretKey);       producerProperties.setProperty(PropertyKeyConst.ONSAddr, CommonConstants.MQ_ONSAddr);       producer = ONSFactory.createProducer(producerProperties);       producer.start();         }    public void sendMessage( String text) {        Message msg = new Message(CommonConstants.MQ_AUTO_TOPIC, CommonConstants.MQ_AUTO_TAG, text.getBytes());        SendResult sendResult = null;        try {            sendResult = producer.send(msg);            System.out.println("Rule MSG_ID:"+sendResult.getMessageId());            logger.info("Rule MSG_ID:"+sendResult.getMessageId());        } catch (Exception e) {         e.printStackTrace();            logger.error(e.getMessage() + String.valueOf(sendResult));        }        // 当消息发送失败时如何处理        if (sendResult == null) {            // TODO        }    }       /**    * Spring bean destroy-method    */   public void destroy() {      producer.shutdown();   }      }
6.新建消费者
package com.mq.tcp;import com.aliyun.openservices.ons.api.Consumer;import com.aliyun.openservices.ons.api.ONSFactory;import com.aliyun.openservices.ons.api.PropertyKeyConst;import com.util.CommonConstants;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import java.util.Properties;/** * MQ 接收消息示例 Demo */public class WithdrawMsgConsumer {   private final Logger logger = LoggerFactory.getLogger(WithdrawMsgProducer.class);   private Consumer consumer;      private String consumerId;   private String accessKey;   private String secretKey;   private String onsAddr;   private String topic;   private String tag;   @Autowired   private WithdrawMessageListener withdrawMessageListener;      public void init() {         Properties consumerProperties = new Properties();        consumerProperties.setProperty(PropertyKeyConst.ConsumerId, CommonConstants.MQ_CID);        consumerProperties.setProperty(PropertyKeyConst.AccessKey, CommonConstants.MQ_AccessKey);        consumerProperties.setProperty(PropertyKeyConst.SecretKey, CommonConstants.MQ_SecretKey);        consumerProperties.setProperty(PropertyKeyConst.ONSAddr, CommonConstants.MQ_ONSAddr);        consumerProperties.put(PropertyKeyConst.ConsumeThreadNums,60);                consumer = ONSFactory.createConsumer(consumerProperties);        consumer.subscribe(CommonConstants.MQ_AUTO_TOPIC, CommonConstants.MQ_AUTO_TAG, withdrawMessageListener);        consumer.start();         }      public void destroy() {      consumer.shutdown();   }   public String getConsumerId() {      return consumerId;   }   public void setConsumerId(String consumerId) {      this.consumerId = consumerId;   }   public String getAccessKey() {      return accessKey;   }   public void setAccessKey(String accessKey) {      this.accessKey = accessKey;   }   public String getSecretKey() {      return secretKey;   }   public void setSecretKey(String secretKey) {      this.secretKey = secretKey;   }   public String getOnsAddr() {      return onsAddr;   }   public void setOnsAddr(String onsAddr) {      this.onsAddr = onsAddr;   }   public String getTopic() {      return topic;   }   public void setTopic(String topic) {      this.topic = topic;   }   public String getTag() {      return tag;   }   public void setTag(String tag) {      this.tag = tag;   }}


原创粉丝点击