Docker安装RocketMQ-4.9.4
从rocketmq-docker项目构建rocketmq的镜像,rocketmq-docker的地址是https://github.com/apache/rocketmq-docker/,克隆项目:
git clone https://github.com/apache/rocketmq-docker.git
cd rocketmq-docker/image-build/
sh build-image.sh RMQ-VERSION BASE-IMAGE
RMQ-VERSION是RocketMQ的版本,可从https://archive.apache.org/dist/rocketmq/查看,BASE-IMAGE是制作镜像的操作系统,从[centos, alpine]之间选择。
输入:
sh build-image.sh 4.9.4 alpine
执行成功后运行docker images查看。
容器内的文件/home/rocketmq/rocketmq-4.9.4/conf/broker.conf,新增下面内容:
brokerIP1=192.168.233.132
namesrvAddr=192.168.233.132:9876
里面的ip地址是宿主机的ip,不加能启动但是发送消息会出错。
下面的启动中用到的宿主机目录的权限必须是777,否则会出错。
启动namesrv:
docker run -d -v /docker/rocketmq/namesrv/logs:/home/rocketmq/logs \
--name mqnamesrv \
-e "JAVA_OPT_EXT=-Xms512M -Xmx512M -Xmn128m" \
-p 9876:9876 \
apache/rocketmq:4.9.4-alpine \
sh mqnamesrv
-d表示容器后台运行,-v path1:path2,path1表示宿主机的路径,path2表示容器的路径,-e "JAVA_OPT_EXT=-Xms512M -Xmx512M -Xmn128m"表示设置容器内的环境变量。-p表示宿主机和容器的端口映射。前一个表示宿主机的端口,后一个表示容器的端口。
启动broker:
docker run -d -v /docker/rocketmq/broker/logs:/home/rocketmq/logs -v /docker/rocketmq/broker/store:/home/rocketmq/store \
-v /docker/rocketmq/broker/conf:/home/rocketmq/conf \
--name rmqbroker \
--link mqnamesrv:namesrv \
-e "JAVA_OPT_EXT=-Xms512M -Xmx512M -Xmn128m" \
-e "NAMESRV_ADDR=namesrv:9876" \
-p 10911:10911 -p 10912:10912 -p 10909:10909 \
apache/rocketmq:4.9.4-alpine \
sh mqbroker -c /home/rocketmq/rocketmq-4.9.4/conf/broker.conf
-c /home/rocketmq/rocketmq-4.9.4/conf/broker.conf是容器内的文件。
测试:
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
@Order(10)
@Component
@Slf4j
public class ProductCommandLine implements CommandLineRunner {
private static final int size = 100;
private static final String TOCPIC_NAME = "test1";
private static final String TAG = "tag";
private static final String CONTENT = "CONTENT";
@Override
public void run(String... args) throws Exception {
DefaultMQProducer producer = new DefaultMQProducer("product_name", false);
producer.setNamesrvAddr("192.168.233.132:9876");
producer.start();
producer.setSendMsgTimeout(60000);
for (int i = 0; i < size; i++) {
Message message =
new Message(TOCPIC_NAME, TAG, (CONTENT + i).getBytes(StandardCharsets.UTF_8));
producer.send(
message,
new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
log.info("send success;" + sendResult);
}
@Override
public void onException(Throwable throwable) {
log.error("send error;" + throwable);
}
});
}
Thread.sleep(10000);
// producer.shutdown();
}
}
用RocketMQ-dashboard查看: