跳至内容

rabbitmq#

RabbitMQ 消息队列。

RabbitMQ消息队列配置 #

基础类: BaseSettings

RabbitMQ消息队列配置。

参数:

名称 类型 描述 默认值
type Literal[str]
'rabbitmq'
url str
'amqp://guest:guest@localhost/'
exchange_name str
'llama-deploy'
username str | None
None
password str | None
None
host str | None
None
port int | None
None
vhost str | None
None
secure bool | None
None
Source code in llama_deploy/message_queues/rabbitmq.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class RabbitMQMessageQueueConfig(BaseSettings):
    """RabbitMQ message queue configuration."""

    model_config = SettingsConfigDict(env_prefix="RABBITMQ_")

    type: Literal["rabbitmq"] = Field(default="rabbitmq", exclude=True)
    url: str = DEFAULT_URL
    exchange_name: str = DEFAULT_EXCHANGE_NAME
    username: str | None = None
    password: str | None = None
    host: str | None = None
    port: int | None = None
    vhost: str | None = None
    secure: bool | None = None

    def model_post_init(self, __context: Any) -> None:
        if self.username and self.password and self.host:
            scheme = "amqps" if self.secure else "amqp"
            self.url = f"{scheme}://{self.username}:{self.password}@{self.host}"
            if self.port:
                self.url += f":{self.port}"
            elif self.vhost:
                self.url += f"/{self.vhost}"

RabbitMQ消息队列 #

基类: AbstractMessageQueue

RabbitMQ与aio-pika客户端的集成。

This class creates a Work (or Task) Queue. For more information on Work Queues with RabbitMQ see the pages linked below: 1. https://aio-pika.readthedocs.io/en/latest/rabbitmq-tutorial/2-work-queues.html 2. https://aio-pika.readthedocs.io/en/latest/rabbitmq-tutorial/3-publish-subscribe.html

连接通过使用amqp uri方案的URL建立:

amqp_URI       = "amqp://" amqp_authority [ "/" vhost ] [ "?" query ]
amqp_authority = [ amqp_userinfo "@" ] host [ ":" port ]
amqp_userinfo  = username [ ":" password ]
username       = *( unreserved / pct-encoded / sub-delims )
password       = *( unreserved / pct-encoded / sub-delims )
vhost          = segment
The Work Queue created has the following properties
  • 交易所名称为 self.exchange
  • 消息通过交换器发布到此队列
  • 消费者会绑定到交换机,并根据其消息类型拥有相应的队列
  • 轮询调度:当多个消费者监听同一个队列时,将按照顺序选择其中一个消费者。

属性:

名称 类型 描述
url str

用于连接到RabbitMQ服务器的amqp URL字符串

exchange_name str

在RabbitMQ AMQP 0-9协议中给所谓的交换器指定的名称。

示例:

from llama_deploy.message_queues.rabbitmq import RabbitMQMessageQueue

message_queue = RabbitMQMessageQueue()  # uses the default url
Source code in llama_deploy/message_queues/rabbitmq.py
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
class RabbitMQMessageQueue(AbstractMessageQueue):
    """RabbitMQ integration with aio-pika client.

    This class creates a Work (or Task) Queue. For more information on Work Queues
    with RabbitMQ see the pages linked below:
        1. https://aio-pika.readthedocs.io/en/latest/rabbitmq-tutorial/2-work-queues.html
        2. https://aio-pika.readthedocs.io/en/latest/rabbitmq-tutorial/3-publish-subscribe.html

    Connections are established by url that use [amqp uri scheme](https://www.rabbitmq.com/docs/uri-spec#the-amqp-uri-scheme):

    ```
    amqp_URI       = "amqp://" amqp_authority [ "/" vhost ] [ "?" query ]
    amqp_authority = [ amqp_userinfo "@" ] host [ ":" port ]
    amqp_userinfo  = username [ ":" password ]
    username       = *( unreserved / pct-encoded / sub-delims )
    password       = *( unreserved / pct-encoded / sub-delims )
    vhost          = segment
    ```

    The Work Queue created has the following properties:
        - Exchange with name self.exchange
        - Messages are published to this queue through the exchange
        - Consumers are bound to the exchange and have queues based on their
            message type
        - Round-robin dispatching: with multiple consumers listening to the same
            queue, only one consumer will be chosen dictated by sequence.

    Attributes:
        url (str): The amqp url string to connect to the RabbitMQ server
        exchange_name (str): The name to give to the so-called exchange within
            RabbitMQ AMQP 0-9 protocol.

    Examples:
        ```python
        from llama_deploy.message_queues.rabbitmq import RabbitMQMessageQueue

        message_queue = RabbitMQMessageQueue()  # uses the default url
        ```
    """

    def __init__(
        self,
        config: RabbitMQMessageQueueConfig | None = None,
        url: str = DEFAULT_URL,
        exchange_name: str = DEFAULT_EXCHANGE_NAME,
        **kwargs: Any,
    ) -> None:
        self._config = config or RabbitMQMessageQueueConfig()
        self._registered_topics: set[str] = set()

    @classmethod
    def from_url_params(
        cls,
        username: str,
        password: str,
        host: str,
        vhost: str = "",
        port: int | None = None,
        secure: bool = False,
        exchange_name: str = DEFAULT_EXCHANGE_NAME,
    ) -> "RabbitMQMessageQueue":
        """Convenience constructor from url params.

        Args:
            username (str): username for the amqp authority
            password (str): password for the amqp authority
            host (str): host for rabbitmq server
            port (int | None, optional): port for rabbitmq server. Defaults to None.
            secure (bool, optional): Whether or not to use SSL. Defaults to False.
            exchange_name (str, optional): The exchange name. Defaults to DEFAULT_EXCHANGE_NAME.

        Returns:
            RabbitMQMessageQueue: A RabbitMQ MessageQueue integration.
        """
        if not secure:
            if port:
                url = f"amqp://{username}:{password}@{host}:{port}/{vhost}"
            else:
                url = f"amqp://{username}:{password}@{host}/{vhost}"
        else:
            if port:
                url = f"amqps://{username}:{password}@{host}:{port}/{vhost}"
            else:
                url = f"amqps://{username}:{password}@{host}/{vhost}"
        return cls(RabbitMQMessageQueueConfig(url=url, exchange_name=exchange_name))

    async def new_connection(self) -> "Connection":
        """Returns a new connection to the RabbitMQ server."""
        return await _establish_connection(self._config.url)

    async def _publish(self, message: QueueMessage, topic: str) -> Any:
        """Publish message to the queue."""
        from aio_pika import DeliveryMode, ExchangeType
        from aio_pika import Message as AioPikaMessage

        connection = await _establish_connection(self._config.url)

        async with connection:
            channel = await connection.channel()
            exchange = await channel.declare_exchange(
                self._config.exchange_name,
                ExchangeType.DIRECT,
            )
            message_body = json.dumps(message.model_dump()).encode("utf-8")

            aio_pika_message = AioPikaMessage(
                message_body,
                delivery_mode=DeliveryMode.PERSISTENT,
            )
            # Sending the message
            await exchange.publish(aio_pika_message, routing_key=topic)
            logger.info(f"published message {message.id_} to {topic}")

    async def register_consumer(
        self, consumer: BaseMessageQueueConsumer, topic: str
    ) -> StartConsumingCallable:
        """Register a new consumer."""
        from aio_pika import Channel, ExchangeType, IncomingMessage, Queue
        from aio_pika.abc import AbstractIncomingMessage

        connection = await _establish_connection(self._config.url)
        async with connection:
            channel = cast(Channel, await connection.channel())
            exchange = await channel.declare_exchange(
                self._config.exchange_name,
                ExchangeType.DIRECT,
            )
            queue = cast(Queue, await channel.declare_queue(name=topic))
            await queue.bind(exchange)

        self._registered_topics.add(topic or consumer.message_type)
        logger.info(
            f"Registered consumer {consumer.id_} for topic: {topic}",
        )

        async def start_consuming_callable() -> None:
            """StartConsumingCallable.

            Consumer of this queue, should call this in order to start consuming.
            """

            async def on_message(message: AbstractIncomingMessage) -> None:
                message = cast(IncomingMessage, message)
                async with message.process():
                    decoded_message = json.loads(message.body.decode("utf-8"))
                    queue_message = QueueMessage.model_validate(decoded_message)
                    await consumer.process_message(queue_message)

            # The while loop will reconnect if the connection is lost
            while True:
                connection = await _establish_connection(self._config.url)
                try:
                    async with connection:
                        channel = await connection.channel()
                        exchange = await channel.declare_exchange(
                            self._config.exchange_name,
                            ExchangeType.DIRECT,
                        )
                        queue = cast(Queue, await channel.declare_queue(name=topic))
                        await queue.bind(exchange)
                        await queue.consume(on_message)
                        await asyncio.Future()
                except asyncio.CancelledError:
                    logger.info(
                        f"Cancellation requested, exiting consumer {consumer.id_} for topic: {topic}"
                    )
                    break
                except Exception as e:
                    logger.error(f"Unexpected error: {e}", exc_info=True)
                    # Wait before reconnecting. Ideally we'd want exponential backoff here.
                    await asyncio.sleep(10)
                finally:
                    if connection:
                        await connection.close()

        return start_consuming_callable

    async def deregister_consumer(self, consumer: BaseMessageQueueConsumer) -> Any:
        """Deregister a consumer.

        Not implemented for this integration, as once the connection/channel is
        closed, the consumer is deregistered.
        """
        pass

    async def cleanup(self, *args: Any, **kwargs: dict[str, Any]) -> None:
        """Perform any clean up of queues and exchanges."""
        connection = await self.new_connection()
        async with connection:
            channel = await connection.channel()
            for queue_name in self._registered_topics:
                await channel.queue_delete(queue_name=queue_name)
            await channel.exchange_delete(exchange_name=self._config.exchange_name)

    def as_config(self) -> BaseModel:
        return RabbitMQMessageQueueConfig(
            url=self._config.url, exchange_name=self._config.exchange_name
        )

from_url_params classmethod #

from_url_params(username: str, password: str, host: str, vhost: str = '', port: int | None = None, secure: bool = False, exchange_name: str = DEFAULT_EXCHANGE_NAME) -> RabbitMQMessageQueue

根据URL参数便捷构建的构造函数。

参数:

名称 类型 描述 默认值
username str

AMQP 认证的用户名

required
password str

AMQP 认证的密码

required
host str

RabbitMQ服务器的主机地址

required
port int | None

rabbitmq服务器的端口。默认为None。

None
secure bool

是否使用SSL。默认为False。

False
exchange_name str

交易所名称。默认为DEFAULT_EXCHANGE_NAME。

DEFAULT_EXCHANGE_NAME

返回:

名称 类型 描述
RabbitMQMessageQueue RabbitMQMessageQueue

RabbitMQ消息队列集成。

Source code in llama_deploy/message_queues/rabbitmq.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
@classmethod
def from_url_params(
    cls,
    username: str,
    password: str,
    host: str,
    vhost: str = "",
    port: int | None = None,
    secure: bool = False,
    exchange_name: str = DEFAULT_EXCHANGE_NAME,
) -> "RabbitMQMessageQueue":
    """Convenience constructor from url params.

    Args:
        username (str): username for the amqp authority
        password (str): password for the amqp authority
        host (str): host for rabbitmq server
        port (int | None, optional): port for rabbitmq server. Defaults to None.
        secure (bool, optional): Whether or not to use SSL. Defaults to False.
        exchange_name (str, optional): The exchange name. Defaults to DEFAULT_EXCHANGE_NAME.

    Returns:
        RabbitMQMessageQueue: A RabbitMQ MessageQueue integration.
    """
    if not secure:
        if port:
            url = f"amqp://{username}:{password}@{host}:{port}/{vhost}"
        else:
            url = f"amqp://{username}:{password}@{host}/{vhost}"
    else:
        if port:
            url = f"amqps://{username}:{password}@{host}:{port}/{vhost}"
        else:
            url = f"amqps://{username}:{password}@{host}/{vhost}"
    return cls(RabbitMQMessageQueueConfig(url=url, exchange_name=exchange_name))

new_connection async #

new_connection() -> Connection

返回一个到RabbitMQ服务器的新连接。

Source code in llama_deploy/message_queues/rabbitmq.py
150
151
152
async def new_connection(self) -> "Connection":
    """Returns a new connection to the RabbitMQ server."""
    return await _establish_connection(self._config.url)

register_consumer async #

register_consumer(consumer: BaseMessageQueueConsumer, topic: str) -> StartConsumingCallable

注册一个新消费者。

Source code in llama_deploy/message_queues/rabbitmq.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
async def register_consumer(
    self, consumer: BaseMessageQueueConsumer, topic: str
) -> StartConsumingCallable:
    """Register a new consumer."""
    from aio_pika import Channel, ExchangeType, IncomingMessage, Queue
    from aio_pika.abc import AbstractIncomingMessage

    connection = await _establish_connection(self._config.url)
    async with connection:
        channel = cast(Channel, await connection.channel())
        exchange = await channel.declare_exchange(
            self._config.exchange_name,
            ExchangeType.DIRECT,
        )
        queue = cast(Queue, await channel.declare_queue(name=topic))
        await queue.bind(exchange)

    self._registered_topics.add(topic or consumer.message_type)
    logger.info(
        f"Registered consumer {consumer.id_} for topic: {topic}",
    )

    async def start_consuming_callable() -> None:
        """StartConsumingCallable.

        Consumer of this queue, should call this in order to start consuming.
        """

        async def on_message(message: AbstractIncomingMessage) -> None:
            message = cast(IncomingMessage, message)
            async with message.process():
                decoded_message = json.loads(message.body.decode("utf-8"))
                queue_message = QueueMessage.model_validate(decoded_message)
                await consumer.process_message(queue_message)

        # The while loop will reconnect if the connection is lost
        while True:
            connection = await _establish_connection(self._config.url)
            try:
                async with connection:
                    channel = await connection.channel()
                    exchange = await channel.declare_exchange(
                        self._config.exchange_name,
                        ExchangeType.DIRECT,
                    )
                    queue = cast(Queue, await channel.declare_queue(name=topic))
                    await queue.bind(exchange)
                    await queue.consume(on_message)
                    await asyncio.Future()
            except asyncio.CancelledError:
                logger.info(
                    f"Cancellation requested, exiting consumer {consumer.id_} for topic: {topic}"
                )
                break
            except Exception as e:
                logger.error(f"Unexpected error: {e}", exc_info=True)
                # Wait before reconnecting. Ideally we'd want exponential backoff here.
                await asyncio.sleep(10)
            finally:
                if connection:
                    await connection.close()

    return start_consuming_callable

deregister_consumer async #

deregister_consumer(consumer: BaseMessageQueueConsumer) -> Any

注销一个消费者。

此集成未实现,因为一旦连接/通道关闭,消费者将被注销。

Source code in llama_deploy/message_queues/rabbitmq.py
241
242
243
244
245
246
247
async def deregister_consumer(self, consumer: BaseMessageQueueConsumer) -> Any:
    """Deregister a consumer.

    Not implemented for this integration, as once the connection/channel is
    closed, the consumer is deregistered.
    """
    pass

清理 async #

cleanup(*args: Any, **kwargs: dict[str, Any]) -> None

执行队列和交换机的任何清理操作。

Source code in llama_deploy/message_queues/rabbitmq.py
249
250
251
252
253
254
255
256
async def cleanup(self, *args: Any, **kwargs: dict[str, Any]) -> None:
    """Perform any clean up of queues and exchanges."""
    connection = await self.new_connection()
    async with connection:
        channel = await connection.channel()
        for queue_name in self._registered_topics:
            await channel.queue_delete(queue_name=queue_name)
        await channel.exchange_delete(exchange_name=self._config.exchange_name)
优云智算