封装架构:
pom配置:
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-client</artifactId>
<version>4.6.1</version>
</dependency>
MQConsumer -- 消费者,相当于消费者配置类,直接返回一个consumer容器,可直接调用,然后使用consumer提供的相关方法
package com.wm.mq;
import lombok.extern.log4j.Log4j2;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Log4j2
@Component
public class MQConsumer {
@Value("${rocketMqConfig.groupName}") //MQ 组名
private String groupName;
@Value("${rocketMqConfig.nameSrvAddr}") //MQ 地址
private String nameSrvAddr;
public DefaultMQPushConsumer consumer(MQTopic mqTopic) {
try {
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer();
consumer.setConsumerGroup(groupName);
consumer.setNamesrvAddr(nameSrvAddr);
consumer.subscribe(mqTopic.topic,mqTopic.tags);
consumer.setMessageModel(MessageModel.CLUSTERING);
return consumer;
} catch (MQClientException e) {
log.error(e);
}
return null;
}
}
MQProducer -- 生产者,提供各类发送消息方法
package com.wm.mq;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
@Log4j2
@Component
public class MQProducer {
private DefaultMQProducer defaultMQProducer;
@Resource
public void setDefaultMQProducer(DefaultMQProducer defaultMQProducer_) {
defaultMQProducer = defaultMQProducer_;
}
/**
* 发送同步消息
* @param mqTopic
* @param msg
* @return
*/
public void send(MQTopic mqTopic, Map<String,Object> msg){
try {
Message sendMsg = new Message(mqTopic.topic, mqTopic.tags, msg.toString().getBytes());
SendResult sendResult = defaultMQProducer.send(sendMsg);
log.info("==> send MqMsg: {}", sendResult);
} catch (Exception e) {
log.error(e);
}
}
/**
* 发送异步消息
* @param mqTopic
* @param msg
*/
public void asyncSend(MQTopic mqTopic, Map<String,Object> msg){
try {
Message sendMsg = new Message(mqTopic.topic, mqTopic.tags, msg.toString().getBytes());
defaultMQProducer.send(sendMsg, new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
log.info("==> send AsyncMqMsg:{} ", sendResult);
}
@Override
public void onException(Throwable e) {
log.error(e);
}
});
}catch (Exception e){
log.error(e);
}
}
/**
* 顺序发送消息(分区key-cid)
* @param mqTopic
* @param cid
* @param msg
*/
public void sendOrderMsg(MQTopic mqTopic, int cid, Map<String,Object> msg) {
try {
Message sendMsg = new Message(mqTopic.topic, mqTopic.tags, msg.toString().getBytes());
defaultMQProducer.send(sendMsg, (list, message, o) -> {
int cid1 = (int) o;
int index = cid1 % list.size();
return list.get(index);
},cid);
} catch (Exception e) {
log.error(e);
}
}
}
MQProducerConf -- 生产者配置类
package com.wm.mq;
import lombok.extern.log4j.Log4j2;
import org.apache.rocketmq.client.exception.MQClientException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Log4j2
@Configuration
public class MQProducerConf {
//组名
@Value("${rocketMqConfig.groupName}")
private String groupName;
//MQ 地址
@Value("${rocketMqConfig.nameSrvAddr}")
private String nameSrvAddr;
//消息体最大尺寸
@Value("${rocketMqConfig.maxMessageSize}")
private Integer maxMessageSize;
//超时时间
@Value("${rocketMqConfig.sendMsgTimeOut}")
private Integer sendMsgTimeOut;
//重试时间
@Value("${rocketMqConfig.retryTimesWhenSendFailed}")
private Integer retryTimesWhenSendFailed;
/**
* mq 生产者配置
* @return producer
* @throws MQClientException
*/
@Bean
public org.apache.rocketmq.client.producer.DefaultMQProducer defaultProducer() throws MQClientException {
org.apache.rocketmq.client.producer.DefaultMQProducer producer = new org.apache.rocketmq.client.producer.DefaultMQProducer();
producer.setProducerGroup(groupName);
producer.setNamesrvAddr(nameSrvAddr);
producer.setVipChannelEnabled(false);
producer.setMaxMessageSize(maxMessageSize);
producer.setSendMsgTimeout(sendMsgTimeOut);
producer.setRetryTimesWhenSendAsyncFailed(retryTimesWhenSendFailed);
producer.start();
log.info("==> rocketmq producer server register");
return producer;
}
}
MQTopic -- mq消息Topic主题枚举类,实现Topic统一管理,方便后期维护
package com.wm.mq;
import lombok.Getter;
@Getter
public enum MQTopic {
FRIEND_MSG("TEST","FRIEND_MSG","还有消息"),
SYS_MSG("TEST","SYS_MSG","系统消息");
public final String topic;
public final String tags;
public final String info;
MQTopic(String topic, String tags, String info) {
this.topic = topic;
this.tags = tags;
this.info = info;
}
}
使用方法:
生产者:
public static void main(String[] args) {
int cid = 1;
Map<String,Onject> msg = new hashMap<>;
msg.put("id",1);
try {
mqProducer.sendOrderMsg(MQTopic.FRIEND_MSG, cid, msg);
} catch (Exception e) {
e.printStackTrace();
}
}
消费者:
public void listenMsg() {
try {
DefaultMQPushConsumer consumer = mqConsumer.consumer(MQTopic.FRIEND_MSG);
consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
consumer.registerMessageListener((MessageListenerOrderly) (list, consumeOrderlyContext) -> {
consumeOrderlyContext.setAutoCommit(true);
ConsumeOrderlyStatus status = ConsumeOrderlyStatus.SUCCESS;
for (MessageExt msg : list) {
System.out.printlf(msg)
}
return status;
});
consumer.start();
} catch (Exception e) {
log.error(e);
}
}