安装
官网下载解压 4.9.4
/etc/profile环境变量: export NAMESRV_ADDR=192.168.10.137:9876
bin下(内存不够时,降低jvm消耗内存):
vim runserver.sh
vim runbroker.sh
conf下broker.conf:
autoCreateTopicEnable=true
启动:
nohup ./mqnamesrv -n 192.168.10.137:9876 &
nohup ./mqbroker -n 192.168.10.137:9876 &
关闭:
./mqshutdown broker
./mqshutdown namesrv
原理
使用
- pom
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-client</artifactId>
<version>4.8.0</version>
</dependency>
- application
rocketmq.name-server=IP:9876
rocketmq.producer.group=test_producer_group
rocketmq.consumer.group=test_consumer_group
rocketmq.topic=test
- producer
@Service
public class Producer {
@Autowired
RocketMQTemplate rocketMQTemplate;
@Value("${rocketmq.topic}")
String topic;
public void sendMessage() {
Message message = new Message();
message.setTopic(topic);
message.setBody(body.getBytes(StandardCharsets.UTF_8));
message.setKeys(date);
rocketMQTemplate.asyncSend(topic, message, new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
logger.info("发送[{}]成功, messageId:[{}], messageKey:[{}]", topic, sendResult.getMsgId(), message.getKeys());
}
@Override
public void onException(Throwable throwable) {
System.out.println("error");
}
});
}
}
- consumer
@Service
@RocketMQMessageListener(consumerGroup = "${rocketmq.consumer.group}", topic = "${rocketmq.topic}", consumeThreadMax = 5)
public class Consumer implements RocketMQListener<Message> {
@Override
public void onMessage(Message message) {
String body = new String(message.getBody(), StandardCharsets.UTF_8);
User user = JSON.parseObject(body, User.class);//FastJSON
logger.info("用户名:[{}], age:[{}]", user.getName(), user.getAge());
}
}