当前位置: 首页>>代码示例>>Python>>正文


Python Stomp.message方法代码示例

本文整理汇总了Python中stompest.sync.Stomp.message方法的典型用法代码示例。如果您正苦于以下问题:Python Stomp.message方法的具体用法?Python Stomp.message怎么用?Python Stomp.message使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在stompest.sync.Stomp的用法示例。


在下文中一共展示了Stomp.message方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Client

# 需要导入模块: from stompest.sync import Stomp [as 别名]
# 或者: from stompest.sync.Stomp import message [as 别名]
class Client(object):
	def __init__(self):
		self.stompest = None
		self.greenlet = None
		self.subscriptions = {}
		self._last_id = 0

	def _next_id(self):
		self._last_id += 1
		return self._last_id

	def connect(self):
		if not self.stompest:
			CONFIG, EXTRA = _get_config()
			self._hostname = EXTRA.get('hostname', None)
			self.stompest = Stomp(CONFIG)

		if self.stompest.session.state != StompSession.DISCONNECTED:
			return

		while True:
			try:
				self.stompest.connect(host=self._hostname)
				logger.info('Connected')
				break
			except StompConnectTimeout:
				continue

		if not self.greenlet:
			self.greenlet = gevent.spawn(self._run)

	def _run(self):
		while True:
			try:
				frame = self.stompest.receiveFrame()
				self.stompest.ack(frame)
				if frame.command == 'ERROR':
					logger.error(frame.info())
				elif frame.command == 'MESSAGE':
					token = self.stompest.message(frame)
					if self.subscriptions.get(token):
						subscription = self.subscriptions[token]
						subscription.call(frame)
					else:
						logger.error("Received a message for %s (%s) but there was no matching subscription."
							% (frame.headers.get(StompSpec.DESTINATION_HEADER, '???'), token))
				else:
					logger.warning("Unknown frame: %s" % frame.info())
				# @todo Handle receipts
			except (gevent.GreenletExit, KeyboardInterrupt):
				# @todo Include a receipt in the disconnect. And instead of breaking right away wait for the
				#       receipt frame before disconnecting and consider waiting on any greenlets we started.
				self.stompest.disconnect()
				break
			except StompConnectionError:
				# We've been disconnected from the server. Try reconnecting to it.
				self.connect()

	def on(self, destination, callback):
		self.connect()
		token = self.stompest.subscribe(destination, {
			StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL,
			StompSpec.ID_HEADER: self._next_id(),
		})
		subscription = Subscription(
			conn=self,
			destination=destination,
			token=token,
			callback=callback
		)
		self.subscriptions[subscription.token] = subscription;

	# @todo consider adding optional support for additional custom headers
	def send(self, cmd, destination):
		self.connect()
		body = json.dumps(cmd)
		headers = {}
		headers[StompSpec.CONTENT_TYPE_HEADER] = 'application/json;charset=UTF-8'
		self.stompest.send(destination, body, headers)

	def join(self):
		try:
			self.connect()
		except (gevent.GreenletExit, KeyboardInterrupt):
			return
		try:
			gevent.joinall([self.greenlet])
		except KeyboardInterrupt:
			self.greenlet.kill(block=True)
开发者ID:dantman,项目名称:gareth,代码行数:91,代码来源:messagebroker.py

示例2: StompClient

# 需要导入模块: from stompest.sync import Stomp [as 别名]
# 或者: from stompest.sync.Stomp import message [as 别名]
class StompClient(BaseComponent):
    """ Send and Receive messages from a STOMP queue """
    channel = "stomp"

    def init(self, host, port, username=None, password=None,
             connect_timeout=3, connected_timeout=3,
             version=StompSpec.VERSION_1_2, accept_versions=["1.0", "1.1", "1.2"],
             heartbeats=(0, 0), ssl_context=None,
             use_ssl=True,
             key_file=None,
             cert_file=None,
             ca_certs=None,
             ssl_version=ssl.PROTOCOL_SSLv23,
             key_file_password=None,
             proxy_host=None,
             proxy_port=None,
             proxy_user=None,
             proxy_password=None,
             channel=channel):
        """ Initialize StompClient.  Called after __init__ """
        self.channel = channel
        if proxy_host:
            LOG.info("Connect to %s:%s through proxy %s:%d", host, port, proxy_host, proxy_port)
        else:
            LOG.info("Connect to %s:%s", host, port)

        if use_ssl and not ssl_context:

            ssl_params = dict(key_file=key_file,
                              cert_file=cert_file,
                              ca_certs=ca_certs,
                              ssl_version=ssl_version,
                              password=key_file_password)
            LOG.info("Request to use old-style socket wrapper: %s", ssl_params)
            ssl_context = ssl_params

        if use_ssl:
            uri = "ssl://%s:%s" % (host, port)
        else:
            uri = "tcp://%s:%s" % (host, port)

        # Configure failover options so it only tries to connect once
        self._stomp_server = "failover:(%s)?maxReconnectAttempts=1,startupMaxReconnectAttempts=1" % uri

        self._stomp_config = StompConfig(uri=self._stomp_server, sslContext=ssl_context,
                                         version=version,
                                         login=username,
                                         passcode=password)

        self._heartbeats = heartbeats
        self._accept_versions = accept_versions
        self._connect_timeout = connect_timeout
        self._connected_timeout = connected_timeout
        Stomp._transportFactory = EnhancedStompFrameTransport
        Stomp._transportFactory.proxy_host = proxy_host
        Stomp._transportFactory.proxy_port = proxy_port
        Stomp._transportFactory.proxy_user = proxy_user
        Stomp._transportFactory.proxy_password = proxy_password
        self._client = Stomp(self._stomp_config)
        self._subscribed = {}
        self.server_heartbeat = None
        self.client_heartbeat = None
        self.ALLOWANCE = 2  # multiplier for heartbeat timeouts

    @property
    def connected(self):
        if self._client.session:
            return self._client.session.state == StompSession.CONNECTED
        else:
            return False

    @property
    def subscribed(self):
        return self._subscribed.keys()

    @property
    def stomp_logger(self):
        return LOG_CATEGORY

    @handler("disconnect")
    def _disconnect(self, receipt=None):
        if self.connected:
            self._client.disconnect(receipt=receipt)
        self._client.close(flush=True)
        self.fire(disconnected(reconnect=False))
        self._subscribed = {}
        return "disconnected"

    def start_heartbeats(self):
        LOG.info("Client HB: %s  Server HB: %s", self._client.clientHeartBeat, self._client.serverHeartBeat)
        if self._client.clientHeartBeat:
            if self.client_heartbeat:
                # Timer already exists, just reset it
                self.client_heartbeat.reset()
            else:
                LOG.info("Client will send heartbeats to server")
                # Send heartbeats at 80% of agreed rate
                self.client_heartbeat = Timer((self._client.clientHeartBeat / 1000.0) * 0.8,
                                              client_heartbeat(), persist=True)
                self.client_heartbeat.register(self)
#.........这里部分代码省略.........
开发者ID:spaceone,项目名称:circuits,代码行数:103,代码来源:client.py


注:本文中的stompest.sync.Stomp.message方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。