到VerneMQ clus的客户端连接

2024-09-30 22:14:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我们建立了一个vernemq3节点集群(https://vernemq.com/docs/clustering/)。在

问题是我没有找到任何关于如何将客户机连接到整个集群的示例。在

例如,对于单个VerneMQ实例,客户机连接(in python)是:

client.connect("xxx.xxx.xxx.xxx", 1883, 60)

其中“xxx.xxx.xxx.xxx“是单个实例的地址。
对于集群,有没有一种方法可以指定整个集群的地址,而不是指向单个节点?在


Tags: 实例inhttpscom示例docs客户机节点
2条回答

使用Paho MQTT client library编写客户机后,我最终使用了客户机类的following扩展:

import random
from paho.mqtt.client import *


class ClusterClient(Client):
    """A subclass of paho.mqtt.Client that supports connecting to a cluster of
       mqtt brokers. connect() and connect_async() additionally accept a list
       of hostnames or host/port tuples:

           connect("host1")

           connect(["host1", "host2", "host3"]) # use default port 1883

           connect(["host1", ("host2", 8883), ("host3", 8883)])

       Hosts to connect to are chosen randomly. If a host disappears the client
       automatically connects to another host from the list.
    """

    def __init__(self, client_id="", clean_session=True, userdata=None,
            protocol=MQTTv311, transport="tcp"):
        super().__init__(client_id, clean_session, userdata, protocol, transport)
        self._hosts = []

    def connect_async(self, host, port=1883, keepalive=60, bind_address=""):
        if isinstance(host, (list, tuple)):
            self._hosts = [(t, 1883) if isinstance(t, str) else t for t in host]
        else:
            self._hosts = [(host, port)]

        for host, port in self._hosts:
            if host is None or len(host) == 0:
                raise ValueError('Invalid host.')
            if port <= 0:
                raise ValueError('Invalid port number.')

        host, port = random.choice(self._hosts)

        super().connect_async(host, port, keepalive, bind_address)

    def reconnect(self):
        hosts = self._hosts[:]
        random.shuffle(hosts)
        while True:
            self._host, self._port = hosts.pop(0)
            try:
                return super().reconnect()
            except socket.error:
                if not hosts:
                    raise 

没有所谓的“整个集群的具体地址”。(对于VerneMQ和任何其他群集服务器软件)。在

如果需要单点联系,则需要集群前面的负载平衡器。然后可以使用不同的负载平衡策略。在

例如,VerneMQ可以很好地与HAProxy配合使用,并且支持代理协议。在

希望这有帮助。在

相关问题 更多 >