基于emqtt搭建一个mqtt的集群服务

构建emqtt的集群

准备docker的镜像

wget -O emqtt-docker http://www.emqtt.com/downloads/2304/docker
docker import < emqtt-docker
#check emqtt-docker image name
docker images
#可以看到镜像名称为:emqttd-docker-v2.3-beta.4

运行emqtt-docker

emqttd_img=emqttd-docker-v2.3-beta.4
#emq nodes
docker run -tid --name emq1 $emqttd_img
docker run -tid --name emq2 $emqttd_img

简单的集群配置
进入emq1节点,运行emqttd_ctl status获得集群节点信息。

docker exec -it emq1 /bin/sh
/opt/emqttd $ emqttd_ctl status
Node '103a1d9fd0df@172.17.0.2' is started
#可以看到node名称为103a1d9fd0df@172.17.0.2
exit

进入到第二节点,并将两个节点join

/opt/emqttd $ docker exec -it emq2 /bin/sh
/opt/emqttd $ emqttd_ctl cluster join 103a1d9fd0df@172.17.0.2
Join the cluster successfully.
Cluster status: [{running_nodes,['103a1d9fd0df@172.17.0.2',
                                 '3a605f1e13b5@172.17.0.3']}]
/opt/emqttd $ emqttd_ctl cluster status

使用负载均衡HAProxy

docker拉取haproxy

#pull haproxy
docker pull haproxy

构建emqtt-haproxy-docker

#https://hub.docker.com/_/haproxy/
mkdir emqtt-haproxy-docker
cd emqtt-haproxy-docker

创建haproxy的配置文件

touch haproxy.cfg
#内容如下(将IP地址改成emq1,emq2的ip地址)
defaults
  log                     global
  option                  dontlognull
  option http-server-close
  retries                 3
  timeout http-request    10s
  timeout queue           1m
  timeout connect         10s
  timeout client          1m
  timeout server          1m
  timeout http-keep-alive 10s
  timeout check           10s

frontend emqtt-front
  bind *:1883
  mode tcp
  default_backend emqtt-backend

backend emqtt-backend
   balance roundrobin
   server emq1 172.17.0.2:1883 check
   server emq2 172.17.0.2:1883 check

frontend emqtt-admin-front
  bind *:18083
  mode http
  default_backend emqtt-admin-backend

backend emqtt-admin-backend
  mode http
  balance roundrobin
  server emq1 172.17.0.2:18083 check
  server emq2 172.17.0.3:18083 check

构建emqtt-haproxy的docker image

touch Dockerfile
echo FROM haproxy:latest > Dockerfile
echo COPY haproxy.cfg /usr/local/etc/haproxy/haproxy.cfg >> Dockerfile
docker build -t emqtt-haproxy .

检测配置并运行

docker run -it --rm --name haproxy-syntax-check emqtt-haproxy haproxy -c -f /usr/local/etc/haproxy/haproxy.cfg

#请指定端口映射1833是tcp服务,18083是dashboard
docker run -d --name emqtt-running-haproxy -p 1883:1883 -p 18083:18083 emqtt-haproxy

使用MQTT.fx客服端测试

下载地址:http://mqttfx.jensd.de/index.php/download
选择local mosquitto,点击链接即可

访问emqtt的Dashboard

http://127.0.0.1:18083/#/

推荐阅读更多精彩内容