Apache RocketMQ 4.2.0 installation and API call tutorial

Installation Environment

  • CentOS 7.0 64bit
  • JDK1.8 64bit

With limited conditions, two (192.168.1.101, 192.168.1.102) virtual machines are used as servers, so 2m-noslave (multi-master mode) is used to run the RocketMQ service

Download and unzip

Select the Huake mirror source and download the compiled installation package (you can also download the RocketMQ project source code and package it with maven)

> wget http://mirrors.hust.edu.cn/apache/rocketmq/4.2.0/rocketmq-all-4.2.0-bin-release.zip

unzip to /usr/localfolder

> sudo unzip rocketmq-all-4.2.0-bin-release.zip -d /usr/local/rocketmq

Modify the folder owner (USERNAME is the system login user name) to avoid executing the startup command without permission

> cd /usr/local/
> sudo chown -R USERNAME: rocketmq

Modify the configuration file

After the two servers are downloaded and installed, modify the MQ configuration file of the machine 192.168.1.101

> vim rocketmq/conf/2m-noslave/broker-a.properties
brokerClusterName=MyCluster
brokerName=broker-a
brokerId=0
deleteWhen=04
fileReservedTime=48
brokerRole=ASYNC_MASTER
flushDiskType=ASYNC_FLUSH
listenPort=10911
namesrvAddr=192.168.1.101:9876;192.168.1.101:9876
brokerIP1=192.168.1.101
storePathCommitLog=/usr/local/rocketmq/store/commitlog
storePathConsumerQueue=/usr/local/rocketmq/store/consumequeue

Modify the MQ configuration file of machine 192.168.1.102

> vim rocketmq/conf/2m-noslave/broker-b.properties
brokerClusterName=MyCluster
brokerName=broker-b
brokerId=0
deleteWhen=04
fileReservedTime=48
brokerRole=ASYNC_MASTER
flushDiskType=ASYNC_FLUSH
listenPort=10911
namesrvAddr=192.168.1.101:9876;192.168.1.101:9876
brokerIP1=192.168.1.102
storePathCommitLog=/usr/local/rocketmq/store/commitlog
storePathConsumerQueue=/usr/local/rocketmq/store/consumequeue

start the service

The two servers start the Name Server respectively

> cd rocketmq
>  nohup sh bin/mqnamesrv &

View the Name Server startup log

> tail -f logs/rocketmqlogs/namesrv.log
INFO main - The Name Server boot success. serializeType=JSON

Start Broker on server 192.168.1.101

> nohup sh mqbroker -c conf/2m-noslave/broker-a.properties  >/dev/null 2>&1 &

Start Broker on server 192.168.1.102

> nohup sh mqbroker -c conf/2m-noslave/broker-b.properties  >/dev/null 2>&1 &

View the Broker startup log

> tail -f logs/rocketmqlogs/broker.log 
INFO main - The broker[broker-a, 192.168.1.101:10911] boot success. serializeType=JSON

shut down service

> sh bin/mqshutdown broker
The mqbroker(36695) is running...
Send shutdown request to mqbroker(36695) OK

> sh bin/mqshutdown namesrv
The mqnamesrv(11786) is running...
Send shutdown request to mqnamesrv(11786) OK

Java API call example

Create a new Maven project and introduce dependency packages

	<dependency>
	    <groupId>org.apache.rocketmq</groupId>
	    <artifactId>rocketmq-client</artifactId>
	    <version>4.2.0</version>
	</dependency>

Producer class, producer, send message

public class Producer {

	private static int count = 100;

	public static void main(String[] args) throws Exception {
		// 设置生产者组名
		DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName");
		// 指定nameServer的地址
		producer.setNamesrvAddr("192.168.1.101:9876;192.168.1.102:9876");
		// 启动实例
		producer.start();

		final Semaphore semaphore = new Semaphore(0);

		for (int i = 0; i < count; i++) {
			Thread.sleep(3000);
			Message message = new Message("TopicTest", 
					"test_tag",
					("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));

			producer.send(message, new SendCallback() {
				public void onSuccess(SendResult sendResult) {
					System.out.println(String.format("message [%s] send success!", new String(message.getBody())));
					semaphore.release();
				}

				public void onException(Throwable throwable) {
					throwable.printStackTrace();
				}
			});

		}
		semaphore.acquire(count);
		//关闭生产者,释放资源
		producer.shutdown();
	}
}

Consumer class, consumer, accepts and processes messages

public class Consumer {

	public static void main(String[] args) throws InterruptedException, MQClientException {
		//设置消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("ConsumerGroupName");
        //设置Consumer第一次启动是从队列头部开始消费还是队列尾部开始消费<br>
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        //指定nameServer的地址
        consumer.setNamesrvAddr("10.0.74.198:9876;10.0.74.199:9876");
        //指定订阅的topic及tag表达式
        consumer.subscribe("TopicTest", "*");
        
		consumer.registerMessageListener(new MessageListenerConcurrently() {
			public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, 
					ConsumeConcurrentlyContext context) {
				MessageExt messageExt = msgs.get(0);
				System.out.println(String.format("Custome message [%s],tagName[%s]", 
						new String(messageExt.getBody()),
						messageExt.getTags()));
				return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
			}
		});
		//启动消费者实例
        consumer.start();
        System.out.println("Consumer Started.");
    }
}

Run the Consumer and Producer in turn, and the console prints the following information

#Producer console info
message [Hello RocketMQ 0] send success!
message [Hello RocketMQ 1] send success!
message [Hello RocketMQ 2] send success!
message [Hello RocketMQ 3] send success!
...
#Consumer console info
Custome message [Hello RocketMQ 0],tagName[test_tag]
Custome message [Hello RocketMQ 1],tagName[test_tag]
Custome message [Hello RocketMQ 2],tagName[test_tag]
Custome message [Hello RocketMQ 3],tagName[test_tag]
...

The common operation error "No Topic Route Info", please check whether the firewall is turned on and release the two ports 9876 and 10911!

Please indicate the source when reprinting, thank you!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325212723&siteId=291194637