一、搭建简单mq(这里用的docker搭建)
这里自行百度很简单
二、整合代码
1、pom引入 <dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-client</artifactId> <version>4.9.4</version> </dependency> <dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-acl</artifactId> <version>4.9.4</version> </dependency> <!--springboot rocketmq依赖 --> <dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-spring-boot-starter</artifactId> <version>2.0.3</version> </dependency>
2、配置
@Data @Configuration @Slf4j public class MQConsumerConfigure { @Autowired private MessageListenerConcurrentlySerivce messageListenerConcurrently; /** * mq 消费者配置 * * @return * @throws MQClientException */ @Bean public DefaultMQPushConsumer defaultConsumer() throws MQClientException { log.info("defaultConsumer 正在创建---------------------------------------"); DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("my-consumer-group"); try { consumer.setNamesrvAddr("101.42.44.109:9876"); // 设置监听 consumer.registerMessageListener(messageListenerConcurrently); consumer.subscribe("RLT_TEST_TOPIC", "tag6"); /** * 设置consumer第一次启动是从队列头部开始还是队列尾部开始 * 如果不是第一次启动,那么按照上次消费的位置继续消费 */ consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET); /** * 设置消费模型,集群还是广播,默认为集群 */ consumer.setMessageModel(MessageModel.CLUSTERING); consumer.start(); } catch (MQClientException e) { log.error("consumer 创建失败!"); } return consumer; } }
3、生产者
@Slf4j @Component public class MQTestProducerService { @Resource private DefaultMQProducer defaultMQProducer; private static final String TAG_SOCKET_MSG = "tag6"; public void sendSocketMsg(String param){ try { String a="555"; Message msg=new Message("RLT_TEST_TOPIC", TAG_SOCKET_MSG, a.getBytes()); msg.putUserProperty("request-id", UUID.randomUUID().toString().replace("-", "")); SendResult sendResult= defaultMQProducer.send(msg); System.out.println("1"); } catch (Exception e) { log.error(e.getMessage()); } } }
4、消费者
@Slf4j @Component public class MessageListenerConcurrentlySerivce implements MessageListenerConcurrently { @Override public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) { System.out.println(); return ConsumeConcurrentlyStatus.RECONSUME_LATER; } }
这样就可以springboot 集成简单的mq啦~~