RocketMq integration of daily use springBoot

       Now use rocketmq basically equipped with spring used in conjunction with, now at springBoot as a demonstration.

1. First to pour the required dependencies

<dependency>
    <groupId>com.alibaba.rocketmq</groupId>
    <artifactId>rocketmq-client</artifactId>
    <version>3.2.6</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.60</version>
</dependency>
备注:这里切记要倒入正确的fastjson包,否则会导致收发消息报错:路由异常说该nameserver下没有配置此topic

2. Start each broker and nameserver

> nohup sh bin/mqnamesrv &
> nohup sh bin/mqbroker -n localhost:9876&
备注:切记一定要先查看自身的ip,启动broker记得查看broker日志是否成功 
broker日志地址:~/logs/rocketmqlogs/broker.log
2019-12-02 13:53:12 INFO brokerOutApi_thread_2 - register broker[0]to name server 192.168.142.80:9876 OK

   View java program process, start to see if there namesev and broker 

>jps

6599 RemoteMavenServer36
6743 BrokerStartup
6747 Jps
6653 Launcher
6670 NamesrvStartup  

3. Stop Nameserver and Broker Services

First, go to the bin directory there will be such a service mqshutdown, of course, there are also just launched the service broker and nameserver

So stop nameServer and Broker command as follows:

(base) bogon:rocketmq-all-4.6.0-bin-release humingming$ sh bin/mqshutdown namesrv  --停止注册发现状态服务
The mqnamesrv(12524) is running...
Send shutdown request to mqnamesrv(12524) OK
(base) bogon:rocketmq-all-4.6.0-bin-release humingming$ sh bin/mqshutdown broker --停止broker服务
The mqbroker(12534) is running...
Send shutdown request to mqbroker(12534) OK
[3]+  Exit 143                nohup sh bin/mqnamesrv

4. Write an example of producers and consumers

package rocketmq.day01;

import com.alibaba.rocketmq.client.exception.MQBrokerException;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.client.producer.DefaultMQProducer;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.common.message.Message;
import com.alibaba.rocketmq.remoting.exception.RemotingException;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author heian
 * @create 2019-11-28-8:23 下午
 * @description
 */
public class ProducerDemo {

    public static void main(String[] args) throws MQClientException {
        DefaultMQProducer producer = new DefaultMQProducer("unique_producer_group__name");
        producer.setNamesrvAddr("192.168.142.80:9876");
        producer.start();
        for (int i = 0; i < 1; i++) {
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat();
            String format = sdf.format(date);
            Message message = new Message("topicName", String.valueOf(i),format.getBytes());
            SendResult sendResult= new SendResult();
            try {
                 sendResult = producer.send(message);
            } catch (RemotingException  |MQBrokerException | InterruptedException e) {
                System.out.println("消息发送失败:" + sendResult.getMsgId());
                e.printStackTrace();
            }
            System.out.println("key:"+i + "消息的发送结果为:" + sendResult.toString() + "消息ID为:" + sendResult.getMsgId());
        }

    }

}
package rocketmq.day01;

import com.alibaba.rocketmq.client.consumer.DefaultMQPushConsumer;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import com.alibaba.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.common.consumer.ConsumeFromWhere;
import com.alibaba.rocketmq.common.message.MessageExt;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @author heian
 * @create 2019-11-28-8:51 下午
 * @description
 */
public class ConsumeDemo {

    public static void main(String[] args) throws MQClientException {
        DefaultMQPushConsumer defaultMQPushConsumer = new DefaultMQPushConsumer("unique_consume_group_name");
        defaultMQPushConsumer.setNamesrvAddr("192.168.142.80:9876");
        // 设置消费地点,从最第一个进行消费(其实就是消费策略)
        defaultMQPushConsumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        defaultMQPushConsumer.subscribe("topicName","*");
        defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                byte[] body = list.get(0).getBody();
                try {
                    String ms = new String(body,"utf-8");
                    System.out.println(Thread.currentThread().getName() + "监听到消息:" + ms);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        defaultMQPushConsumer.start();
    }

}

5. Start producers and consumers, respectively, 

Console print information is as follows:

--生产者控制台
key:0消息的发送结果为:SendResult [sendStatus=SEND_OK, msgId=C0A88E5000002A9F0000000000070774, messageQueue=MessageQueue [topic=topicName, brokerName=bogon, queueId=0], queueOffset=20]消息ID为:C0A88E5000002A9F0000000000070774
--消费者控制台
ConsumeMessageThread_1监听到消息:19-12-2 下午2:00

 Note: You can find before and after a message is sent must be defined

  1. GroupName (production and consumption group name group name)
  2. NameServer address and port (broker must be registered with the Nmaesrv, somewhat similar nio in serverSocketChannel.register (selector, 0)), is to open a channel server, client within the channel to write data to a server with a selector multi-monitor multiple clients
  3. topic name tags or finer

Furthermore: 1.rocketmq write queue default is 8, the production configuration is twice the number of instances in accordance with, such as a micro-8 production services, is generally configured to read and write queues 16

           2. The consumer side thread monitor default is the largest since 20 threads listening

Graphical interface for managing cluster mq

        For rocketmq novices if we want to see some news or some track information topic, ah, use the command mqadmin a little unrealistic ( mqadmin command ), so they need a similar navicat same visual interface.

       Operation and maintenance services is a springboot project, you need to download from GitHub address: https://github.com/apache/rocketmq-externals   after entering we need to download these components locally, only rocketmq-console we use this project file folder.

  1. You can use the idea to open itself to see its source code, in this boot project and a properties file, configure namesrv address to its own IP address: rocketmq.config.namesrvAddr = localhost: 9876 is clustered deployment if the ip: 9876; ip2; 9876
  2. The boot project labeled jar package using the direct command: Go to / Users / humingming / IdeaProjects / rocketmq-console folder execute this command
    编译命令:mvn clean package -Dmaven.test.skip=true(注意:不要直接使用mvn package,会提示很多错误)

    It generates a target file from the boot project folder and which generates a jar file, we mainly use is this: rocketmq-console-ng-1.0.1.jar

  3.  The jar is switched to run directly package directory: java -jar rocketmq-console-ng-1.0.1.jar These commands can be entered directly on the idea, the jar packets directly packaged and operation

    java -jar rocketmq-console-ng-1.0.1.jar
    

    NOTE: If ip address is incorrect, or port conflict, you can add a suffix behind running jar

  4. Direct access to running good jar (in fact, running a sprongboot project)  HTTP: // localhost: 8080 /

    At this point, open our rocketmq learning journey! ! !

 

 

Published 73 original articles · won praise 18 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_40826106/article/details/103347083