python接收solace管道信息

从git里抄了抄,能用就行。

安装依赖:

autopep8==1.6.0
certifi==2020.12.5
chardet==4.0.0
idna==2.10
pycodestyle==2.8.0
requests==2.25.1
solace-pubsubplus==1.6.0
toml==0.10.2
urllib3==1.26.4

autopep8==1.6.0
chardet==4.0.0
pycodestyle==2.8.0
solace-pubsubplus==1.6.0
toml==0.10.2

官方git里抄的类:

import threading
from datetime import datetime
import time
from concurrent.futures.thread import ThreadPoolExecutor
from typing import TypeVar
from solace.messaging.messaging_service import MessagingService
from solace.messaging.config.solace_properties import transport_layer_properties, service_properties, \
    authentication_properties
from solace.messaging.config.solace_properties.message_properties import CORRELATION_ID, PRIORITY
from solace.messaging.receiver.inbound_message import InboundMessage
from solace.messaging.resources.queue import Queue
from solace.messaging.resources.topic import Topic
from solace.messaging.resources.topic_subscription import TopicSubscription
import os

class SamplerBoot:
    """this class is created for instantiating the broker properties from environment"""

    properties_from_external_file_name = 'solbroker_properties.json'

    solbroker_properties_key = 'solbrokerProperties'
    host_secured = 'solace.messaging.transport.host.secured'
    host_compressed = 'solace.messaging.transport.host.compressed'

    valid_certificate_authority = 'public_root_ca'

    @staticmethod
    def read_solbroker_props(external_kvps: dict):
        """Read Solbroker properties from external source"""
        if SamplerBoot.solbroker_properties_key not in external_kvps:
            print(f'Solbroker details in '
                  f'[{SamplerBoot.properties_from_external_file_name}] is unavailable, '
                  f'unable to find KEY: [{SamplerBoot.solbroker_properties_key}]. Refer README...')

        broker_properties = external_kvps[SamplerBoot.solbroker_properties_key]

        if not all(key in broker_properties for key in (transport_layer_properties.HOST,
                                                        SamplerBoot.host_secured,
                                                        service_properties.VPN_NAME,
                                                        authentication_properties.SCHEME_BASIC_USER_NAME,
                                                        authentication_properties.SCHEME_BASIC_PASSWORD)):
            print(f'Solbroker details in '
                  f'[{SamplerBoot.properties_from_external_file_name}] '
                  f'is unavailable, unable to find anyone of following KEYs: '
                  f'[{transport_layer_properties.HOST}/{service_properties.VPN_NAME}/'
                  f'{authentication_properties.SCHEME_BASIC_USER_NAME}/'
                  f'{authentication_properties.SCHEME_BASIC_PASSWORD}]. Refer README...')
        print(
            f"\n\n********************************BROKER PROPERTIES**********************************************"
            f"\nFrom external file: '{SamplerBoot.properties_from_external_file_name}': "
            f"\nHost: {broker_properties[transport_layer_properties.HOST]}"
            f"\nSecured Host: {broker_properties[SamplerBoot.host_secured]}"
            f"\nCompressed Host: {broker_properties[SamplerBoot.host_compressed]}"
            f"\nVPN:{broker_properties[service_properties.VPN_NAME]}"
            f"\nUsername: {broker_properties[authentication_properties.SCHEME_BASIC_USER_NAME]}\nPassword: <hidden>"
            f"\n***********************************************************************************************\n")
        return broker_properties

    @staticmethod
    def read_config():
        try:

            return {
                "solbrokerProperties": {
                    "solace.messaging.transport.host": "your host",
                    "solace.messaging.transport.host.secured": "your host",
                    "solace.messaging.transport.host.compressed": "your host",
                    "solace.messaging.service.vpn-name": "default",
                    "solace.messaging.authentication.basic.username": "your username",
                    "solace.messaging.authentication.basic.password": "your password"
                }

            }
        except Exception as exception:
            raise Exception(str(exception))


    @staticmethod
    def broker_properties():
        """method to read the properties from external file
        Returns:
            broker properties
        """
        try:
            props_from_file = SamplerBoot.read_config()
            props = SamplerBoot.read_solbroker_props(props_from_file)
            props.pop(SamplerBoot.host_secured, None)
            return props
        except Exception as e:
            raise Exception(str(e))

建立persistent_receiver并订阅topic:

boot = SamplerBoot()
messaging_service = MessagingService.builder().from_properties(boot.broker_properties()).build()
messaging_service.connect()

# Define Topic subscriptions 
topics_sub = TopicSubscription.of("your topic")

# Queue name. This assumes that a persistent queue already exists on the broker with the right topic subscription 
durable_exclusive_queue = Queue.durable_exclusive_queue("your queue")					

# Create a PersistentMessageReceiver Builder which allows you to create a PersistentMessageReceiver  and start it
persistent_receiver= messaging_service.create_persistent_message_receiver_builder() \
               .build(durable_exclusive_queue)

# Start starts the configured PersistentMessageReceiver synchronously. Before this function is called, the receiver is considered off-duty
persistent_receiver.start()	
persistent_receiver.add_subscription(topics_sub)

接收消息,我这边消息数量不多,所以设置的timeout=10000,如果接收到消息就接受并print:

while True:
    try:
        received_message: 'InboundMessage' = persistent_receiver.receive_message(timeout=10000) 
        if received_message:
            NOW = datetime.now()
            payload_as_bytes = received_message.get_payload_as_bytes()
            payload_as_string = received_message.get_payload_as_string()
            print(payload_as_string)
            print(payload_as_bytes)
            persistent_receiver.ack(received_message)
    except Exception as e:
        print(str(e))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值