rocketmq 入门(二)实战demo

参考文章:RocketMQ实战

启动rocketmq的namesrv

启动rocketmq的broker

创建一个简单的springboot项目

pom


    4.0.0

    com.squid.rocketmq
    rocketmq-test
    1.0-SNAPSHOT

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.0.RELEASE
    

    
        
            org.apache.rocketmq
            rocketmq-common
            4.3.2
        
        
        
            org.apache.rocketmq
            rocketmq-client
            4.3.2
        

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


application.yml

#server.port=8080
#server.tomcat.uri-encoding=utf-8
server:
  port: 8080
  tomcat:
    uri-encoding: utf-8

apache:
  rocketmq:
    ###MQ服务器地址
    namesrvAddr: localhost:9876
    producer:
      ###生产者分组
      producerGroup: myProducer
    ###消费者名称
    consumer:
      PushConsumer: myPushConsumer1
      consumerGroup: xxx

producer

@Service
public class ProducerServiceImpl {
    @Value("${apache.rocketmq.producer.producerGroup}")
    private String producerGroup;

    @Value("${apache.rocketmq.namesrvAddr}")
    private String namesrvAddr;

    private DefaultMQProducer producer;

    @PostConstruct
    public void initProducer() {
        producer = new DefaultMQProducer(producerGroup);
        producer.setNamesrvAddr(namesrvAddr);
        /**
         * 默认超时时间3000ms,修改为10000ms
         */
        producer.setSendMsgTimeout(10000);
        producer.setRetryTimesWhenSendFailed(3);
        try {
            producer.start();
            System.out.println("[Producer 已启动]");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String send(String topic, String tags, String msg) {
        SendResult result = null;
        try {
            Message message = new Message(topic, tags, msg.getBytes(RemotingHelper.DEFAULT_CHARSET));
            result = producer.send(message);
            System.out.println("[Producer] msgID(" + result.getMsgId() + ") " + result.getSendStatus());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "{\"MsgId\":\"" + result.getMsgId() + "\"}";
    }

    @PreDestroy
    public void shutDownProducer() {
        if (producer != null) {
            producer.shutdown();
        }
    }
}

consumer

@Configuration
public class ConsumerListener {

    @Value("${apache.rocketmq.consumer.consumerGroup}")
    private String consumerGroup;
    @Value("${apache.rocketmq.namesrvAddr}")
    private String namesrvAddr;

    @Bean
    public DefaultMQPushConsumer defaultMQPushConsumer() {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(consumerGroup);
        consumer.setNamesrvAddr(namesrvAddr);
        try {
            //广播模式消费
            //consumer.setMessageModel(MessageModel.BROADCASTING);
            consumer.subscribe("MqController", "*");

            // 如果是第一次启动,从队列头部开始消费
            // 如果不是第一次启动,从上次消费的位置继续消费
            consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
            consumer.registerMessageListener((MessageListenerConcurrently) (list, context) -> {
                try {
                    for (MessageExt messageExt : list) {
                        String messageBody = new String(messageExt.getBody(), RemotingHelper.DEFAULT_CHARSET);
                        System.out.println("[Consumer] msgID(" + messageExt.getMsgId() + ") msgBody : " + messageBody);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            });
            consumer.start();
            System.out.println("[Consumer 已启动]");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return consumer;
    }
}

Controller

@Controller
@RequestMapping(value = "/mq")
public class MqController {
    @Autowired
    private ProducerServiceImpl producer;

    @RequestMapping(value = "/push",method = RequestMethod.GET)
    @ResponseBody
    public String test(){
        producer.send("TopicTest", "push", "测试消息");
        return "MqController ok!";
    }
}

本地启动springboot,访问localhost:8080/mq/push打印出ok,ide控制台打印出:

[Producer] msgID(C0A800A328D018B4AAC24138AAA20000) SEND_OK
[Consumer] msgID(C0A800A328D018B4AAC24138AAA20000) msgBody : 测试消息
成功!

完成demo链接:https://github.com/Squidyu/rocketmq-test

你可能感兴趣的:(rocketmq)