1 下载部署 RocketMQ
进入 Apache RocketMQ官网 下载你需要的版本的二进制或者源码(需要手动编译)。
如果选择 Source 需要自己编译
解压或者编译好 RocketMQ-4.5.2,并将对应的 RocketMQ 文件目录添加到 Windows 环境变量中。
# 切换到 RocketMQ 的 bin 目录
cd C:UsersAdministratorVideosRocketMQ-4.5.2bin
# 启动 RocketMQ nameserver
start mqnamesrv.cmd
# 启动 RocketMQ broker
start mqbroker.cmd -n 127.0.0.1:9876 autoCreateTopicEnable=true
# 关闭 RocketMQ nameserver
mqshutdown.cmd namesrv
# 关闭 RocketMQ broker
mqshutdown.cmd broker
使用Git克隆或者直接下载 Apache RocketMQ 工具集。
切换到 rocketmq-console 的目录,找到 application.properties ,按自己的实际情况修改 rocketmq-console 的配置。
server.cOntextPath=
server.port=8077
### SSL setting
#server.ssl.key-store=classpath:rmqcngkeystore.jks
#server.ssl.key-store-password=rocketmq
#server.ssl.keyStoreType=PKCS12
#server.ssl.keyAlias=rmqcngkey
#spring.application.index=true
spring.application.name=rocketmq-console
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
logging.cOnfig=classpath:logback.xml
#if this value is empty,use env value rocketmq.config.namesrvAddr NAMESRV_ADDR | now, you can set it in ops page.default localhost:9876
rocketmq.config.namesrvAddr=
#if you use rocketmq version <3.5.8, rocketmq.config.isVIPChannel should be false.default true
rocketmq.config.isVIPChannel=
#rocketmq-console's data path:dashboard/monitor
rocketmq.config.dataPath=/tmp/rocketmq-console/data
#set it false if you don't want use dashboard.default true
rocketmq.config.enableDashBoardCollect=true
#set the message track trace topic if you don't want use the default one
rocketmq.config.msgTrackTopicName=
rocketmq.config.ticketKey=ticket
#Must create userInfo file: ${rocketmq.config.dataPath}/users.properties if the login is required
rocketmq.config.loginRequired=false
切换到 rocketmq-console 的目录
# 1
cd C:UsersAdministratorVideosrocketmq-externals-masterrocketmq-console
# 2
mvn clean package -Dmaven.test.skip=true
编译完成后 rocketmq-console 的目录会多出一个 target 目录,进入 target 目录,使用Java CMD 命令运行 rocketmq-console
cd target
java -jar rocketmq-console-ng-1.0.1.jar
C:UsersAdministratorVideosRocketMQ-4.5.2bin>jps
10056 NamesrvStartup
12424 jar
13160
11228 BrokerStartup
13580 Jps
3 SpringBoot-2.X 整合 RocketMQ
<dependency>
<groupId>org.apache.rocketmqgroupId>
<artifactId>rocketmq-clientartifactId>
<version>4.5.2version>
dependency>
#producer 该应用是否启用生产者
rocketmq.producer.isOnOff=on
#发送同一类消息的设置为同一个group,保证唯一,默认不需要设置,rocketmq会使用ip@pid(pid代表jvm名字)作为唯一标示
rocketmq.producer.groupName=producer
#mq的nameserver地址
rocketmq.producer.namesrvAddr=127.0.0.1:9876
#消息最大长度 默认1024*4(4M)
rocketmq.producer.maxMessageSize=4096
#发送消息超时时间,默认3000
rocketmq.producer.sendMsgTimeout=3000
#发送消息失败重试次数,默认2
rocketmq.producer.retryTimesWhenSendFailed=2
#consumer 该应用是否启用消费者
rocketmq.consumer.isOnOff=on
rocketmq.consumer.groupName=test_consumer
#mq的nameserver地址
rocketmq.consumer.namesrvAddr=127.0.0.1:9876
#该消费者订阅的主题和tags
rocketmq.consumer.topics=test_topic
rocketmq.consumer.consumeThreadMin=20
rocketmq.consumer.consumeThreadMax=64
#设置一次消费消息的条数,默认为1条
rocketmq.consumer.consumeMessageBatchMaxSize=1
package com.xu.springboot.rocketmq;
import java.util.UUID;
import javax.annotation.PostConstruct;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class ProducerConfigure {
/**
* 生产者组名
*/
@Value("${rocketmq.producer.groupName}")
private String producerGroup;
/**
* namesrvAddr
*/
@Value("${rocketmq.producer.namesrvAddr}")
private String namesrvAddr;
private DefaultMQProducer producer;
public DefaultMQProducer getProducer() {
return this.producer;
}
@PostConstruct
public void init() {
producer = new DefaultMQProducer(producerGroup);
//NamesrvAddr 有多个 可以 producer.setNamesrvAddr("127.0.0.1:9876;192.168.0.1:9876;192.168.0.2:9876")
producer.setNamesrvAddr(namesrvAddr);
producer.setVipChannelEnabled(false);
//防止 InstanceName 重复
producer.setInstanceName(UUID.randomUUID().toString());
try {
//producer 在使用前必须调用 start() 只能初始化一次
producer.start();
} catch (Exception e) {
e.printStackTrace();
producer.shutdown();
}
}
}
package com.xu.springboot.rocketmq;
import java.util.UUID;
import javax.annotation.PostConstruct;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class ConsumerConfigure {
/**
* 消费者者组名
*/
@Value("${rocketmq.consumer.groupName}")
private String consumerGroup;
/**
* namesrvAddr
*/
@Value("${rocketmq.consumer.namesrvAddr}")
private String namesrvAddr;
private DefaultMQPushConsumer consumer;
public DefaultMQPushConsumer getProducer() {
return this.consumer;
}
@PostConstruct
public void consumer() {
consumer = new DefaultMQPushConsumer(consumerGroup);
//NamesrvAddr 有多个 可以 producer.setNamesrvAddr("127.0.0.1:9876;192.168.0.1:9876;192.168.0.2:9876")
consumer.setNamesrvAddr(namesrvAddr);
//防止 InstanceName 重复
consumer.setInstanceName(UUID.randomUUID().toString());
try {
consumer.subscribe("test_topic", "*");
consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
consumer.registerMessageListener((MessageListenerConcurrently)(list,context)->{
try {
for(MessageExt msg:list) {
System.out.println("消费者:MsgId = "+msg.getMsgId()+"t消费内容: SendStatus = "+new String(msg.getBody(),RemotingHelper.DEFAULT_CHARSET));
}
} catch (Exception e) {
return ConsumeConcurrentlyStatus.RECONSUME_LATER;
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
});
consumer.start();
} catch (Exception e) {
consumer.shutdown();
}
}
}
监听器属于SpringMVC所以需要在启动内中加入@ServletComponentScan(“com.xu.springboot.listener”)
package com.xu.springboot.listener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionIdListener;
import org.springframework.stereotype.Component;
import com.xu.springboot.rocketmq.ConsumerConfigure;
@Component
public class Consumer extends ConsumerConfigure implements HttpSessionIdListener {
@Override
public void sessionIdChanged(HttpSessionEvent se, String oldSessionId) {
super.consumer();
}
}
修改启动类代码加入 @ServletComponentScan(“com.xu.springboot.listener”) Application.java
package com.xu.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication
@ServletComponentScan("com.xu.springboot.listener")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
package com.xu.springboot.controller;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xu.springboot.rocketmq.ProducerConfigure;
@Controller
@RequestMapping("/rocketmq")
public class RocketMQController {
@Autowired
private ProducerConfigure producer;
@RequestMapping("/order1")
@ResponseBody
public Object order1(String msg,String tag) throws Exception {
Message message=new Message("test_topic",tag,msg.getBytes(RemotingHelper.DEFAULT_CHARSET));
SendResult result=producer.getProducer().send(message);
System.out.println("生产者:MsgId = "+result.getMsgId()+"t发送状态:SendStatus = "+result.getSendStatus());
return result.getSendStatus();
}
@RequestMapping("/order2")
@ResponseBody
public void order2(String msg,String tag) throws Exception {
Message message=new Message("test_topic",tag,msg.getBytes(RemotingHelper.DEFAULT_CHARSET));
producer.getProducer().send(message,new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
System.out.println("生产者:MsgId = "+sendResult.getMsgId()+"t发送状态:SendStatus = "+sendResult.getSendStatus());
}
@Override
public void onException(Throwable e) {
System.out.println("发送失败");
}
});
}
}