linux中RocketMQ安装(单机版)及springboot中的使用
在Linux环境下安装RocketMQ单机版并在Spring Boot中使用的步骤如下:
- 安装Java环境,确保
java
命令可用。 下载RocketMQ二进制包:
wget https://archive.apache.org/dist/rocketmq/4.9.2/rocketmq-all-4.9.2-bin-release.zip
解压RocketMQ压缩包:
unzip rocketmq-all-4.9.2-bin-release.zip
配置环境变量,在
.bashrc
或.bash_profile
中添加:export ROCKETMQ_HOME=/path/to/rocketmq-all-4.9.2-bin-release export PATH=$PATH:$ROCKETMQ_HOME/bin
启动NameServer:
nohup sh mqnamesrv &
启动Broker:
nohup sh mqbroker &
创建Spring Boot项目,添加依赖:
<dependencies> <dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-spring-boot-starter</artifactId> <version>2.2.1</version> </dependency> </dependencies>
在
application.properties
中配置RocketMQ:spring.rocketmq.name-server=127.0.0.1:9876 spring.rocketmq.producer.group=my-group
发送消息的示例代码:
@Service public class ProducerService { @Autowired private RocketMQTemplate rocketMQTemplate; public void sendMessage(String topic, String message) { rocketMQTemplate.convertAndSend(topic, message); } }
接收消息的示例代码:
@Service @RocketMQMessageListener(topic = "your-topic", consumerGroup = "your-consumer_group") public class ConsumerService implements RocketMQListener<String> { @Override public void onMessage(String message) { // 处理接收到的消息 System.out.println("Received message: " + message); } }
确保你的防火墙设置允许使用的端口(默认是9876
),并且RocketMQ服务正常运行。以上步骤安装了RocketMQ并在Spring Boot中进行了配置和消息的发送与接收。
评论已关闭