一、安装RocketMQ
- 解压
unzip rocketmq-all-4.7.1-bin-release.zip
- 启动
nohup ./bin/mqnamesrv &
- 检查启动情况
netstat -an | grep 9876
- 启动Broker
启动之前需要编辑配置文件,修改 JVM 内存设置,默认给的内存 4 GB,超过我们虚拟机的 JVM 了。
cd bin
vim runserver.sh
vim runbroker.sh
启动Broker
nohup ./mqbroker -n localhost:9876 &
查看日记
tail -f ~/logs/rocketmqlogs/broker.log
- 测试RocketMQ
消息发送
cd bin
export NAMESRV_ADDR=localhost:9876
./tools.sh org.apache.rocketmq.example.quickstart.Producer
消息接受
cd bin
export NAMESRV_ADDR=localhost:9876
./tools.sh org.apache.rocketmq.example.quickstart.Consumer
- 关闭RocketMQ
cd bin
./mqshutdown broker
./mqshutdown namesrv
二、安装RocketMQ控制台
- 解压,修改配置文件,打包(控制台是用spring boot写的)
mvn clean package -Dmaven.test.skip=true
2. 进入 target 启动 jar
java -jar rocketmq-console-ng-1.0.0.jar
打开浏览器访问 localhost:9877,如果报错。这是因为我们的 RocketMQ 安装在 Linux 中,控制台在windows,Linux 需要开放端口才能访问,开放 10909 和9876 端口。
firewall-cmd --zone=public --add-port=10909/tcp
--permanent
firewall-cmd --zone=public --add-port=9876/tcp
--permanent
systemctl restart firewalld.service
firewall-cmd --reload
三、Spring Boot整合RocketMQ
provider
- pom.xml
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-bootstarter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-client</artifactId>
<version>4.7.0</version>
</dependency>
- application.xml
rocketmq:
name-server: 192.168.248.129:9876
producer:
group: myprovider
- Order
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Order {
private Integer id;
private String buyerName;
private String buyerTel;
private String address;
private Date createDate;
}
- Controller
@Autowired
private RocketMQTemplate rocketMQTemplate;
@GetMapping("/create")
public Order create(){
Order order = new Order(
1,
"张三",
"123123",
"软件园",
new Date()
);
this.rocketMQTemplate.convertAndSend("myTopic",order);
return order;
}
consumer
- pom.xml
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-bootstarter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-client</artifactId>
<version>4.7.0</version>
</dependency>
- application.xml
rocketmq:
name-server: 192.168.248.129:9876
- Service
@Slf4j
@Service
@RocketMQMessageListener(consumerGroup = "myConsumer",topic = "myTopic")
public class SmsService implements RocketMQListener<Order> {
@Override
public void onMessage(Order order) {
log.info("新订单{},发短信",order);
}
}