SpringBoot集成RocketMQ(完整demo)

RocketMQ本地源码安装https://blog.csdn.net/supreme000/article/details/109117577

RocketMQ可视化控制台rocketmq-externals安装https://blog.csdn.net/supreme000/article/details/109156523

以上两步都完成后,将RocketMQ集成到SpringBoot中

新建一个SpringBoot工程

pom文件如下



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.3.4.RELEASE
         
    
    com.example
    rocketmq-demo
    0.0.1-SNAPSHOT
    rocketmq-demo
    Demo project for Spring Boot

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        

        
            org.apache.rocketmq
            rocketmq-client
            4.4.0
        

    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


在RocketMQConfig中定义nameserver服务的地址与RocketMQ的topic

package com.example.rocketmqdemo.config;

public class RocketMQConfig {

    public static final String NAME_SERVER = "192.168.135.130:9876";

    public static final String TOPIC = "mq_test_topic";

}

生产者

package com.example.rocketmqdemo.jms;

import com.example.rocketmqdemo.config.RocketMQConfig;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.stereotype.Component;

@Component
public class Producer {

    private String producerGroup = "producer_group";

    private DefaultMQProducer producer;

    public Producer(){
        producer = new DefaultMQProducer(producerGroup);
        //指定nameserver地址,多个地址使用,分隔
        producer.setNamesrvAddr(RocketMQConfig.NAME_SERVER);
        start();
    }

    public DefaultMQProducer getProducer(){
        return this.producer;
    }

    public void start(){
        try {
            this.producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public void shutdown(){
        this.producer.shutdown();
    }
}

新建一个controller,在controller中调用生产者发送消息

package com.example.rocketmqdemo.controller;

import com.example.rocketmqdemo.config.RocketMQConfig;
import com.example.rocketmqdemo.jms.Producer;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    private Producer producer;

    @GetMapping(value = "/test")
    public Object test(String msg) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        String str = "Hello World,My First RocketMQ Message=" + msg;
        Message message = new Message(RocketMQConfig.TOPIC, "tag1", str.getBytes());
        SendResult sendResult = producer.getProducer().send(message);
        System.out.println(sendResult);
        return sendResult.toString();
    }
}

消费者

package com.example.rocketmqdemo.jms;

import com.example.rocketmqdemo.config.RocketMQConfig;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class Consumer {

    private DefaultMQPushConsumer consumer;

    private String consumerGroup = "consumer_group";

    public Consumer() throws MQClientException {
        consumer = new DefaultMQPushConsumer(consumerGroup);
        consumer.setNamesrvAddr(RocketMQConfig.NAME_SERVER);
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        consumer.subscribe(RocketMQConfig.TOPIC, "*");

        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List msgs, ConsumeConcurrentlyContext context) {
                try{
                    Message message = msgs.get(0);
                    System.out.println("RocketMQ消费者收到消息,当前线程名称:" + Thread.currentThread().getName() + ",收到的消息是:" + new String(message.getBody()));

                    String topic = message.getTopic();
                    String tags = message.getTags();
                    String keys = message.getKeys();
                    String body = new String(message.getBody(), "utf-8");

                    System.out.println("消息主题是:" + topic + ",标签是:" + tags + "消息唯一标识是:" + keys + "消息内容:" + body);
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }catch (Exception e){
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;

                }
            }
        });

        consumer.start();
        System.out.println("消费者启动");
    }

}

启动类

package com.example.rocketmqdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RocketmqDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(RocketmqDemoApplication.class, args);
    }

}

启动工程,请求接口

SpringBoot集成RocketMQ(完整demo)_第1张图片

消费者收到消息

在RocketMQ控制台根据MessageId搜索消息

SpringBoot集成RocketMQ(完整demo)_第2张图片

查询结果

SpringBoot集成RocketMQ(完整demo)_第3张图片

消费成功

完整代码

链接:https://pan.baidu.com/s/1hGXlBksMDvsiKJIl7oaMXA 
提取码:7am1 

你可能感兴趣的:(rocketMQ,java,rocketMQ)