示例#1
0
from stompest.config import StompConfig
from stompest.sync import Stomp

client = Stomp(StompConfig('tcp://activemq:61613'))
client.connect()
client.send('/queue/test', 'request sent')
client.disconnect()

示例#2
0
def send_stomp(message):
    config = StompConfig(stomp_uri)
    client = Stomp(config)
    client.connect()
    client.send(stomp_destination, message)
    client.disconnect()
示例#3
0
from stompest.config import StompConfig
from stompest.sync import Stomp

CONFIG = StompConfig('tcp://localhost:61613')
QUEUE = '/queue/test'

if __name__ == '__main__':
    client = Stomp(CONFIG)
    client.connect()
    client.send(QUEUE, 'test message 1')
    client.send(QUEUE, 'test message 2')
    client.disconnect()
示例#4
0
def send_score_to_message_queue(date, score):
    client = Stomp(StompConfig('tcp://fmapiclient.cs.ucl.ac.uk:7672', version=StompSpec.VERSION_1_0))
    client.connect(headers={'passcode': 'admin', 'login': '******'})
    message = 'date={0}\nvalue={1}'.format(date, str(score))
    client.send('/queue/PubModelScore.Q', body=message)
    client.disconnect()
示例#5
0
from stompest. async import Stomp
from stompest. async .listener import SubscriptionListener
from stompest.config import StompConfig
from stompest.protocol import StompSpec
from twisted.internet import defer, reactor, threads

from Scheduler import settings as se
from Scheduler.session import getSession
from common.log import Logger
from request_ancheng.request_premium import get_premium
'''
监听车牌号队列
'''
ERROR_QUEUE = '/queue/testConsumerError'
CONFIG = StompConfig(se.i_config.MQHOST)
BATCH_ANCHENG_QUEUE = se.BATCH_ANCHENG_QUEUE

log = Logger()


class Consumer(object):
    @defer.inlineCallbacks
    def runrealtime(self):
        try:
            client = Stomp(CONFIG)
            yield client.connect()
            headers = {
                StompSpec.ACK_HEADER: StompSpec.ACK_AUTO,
                'activemq.prefetchSize': '100',
            }
示例#6
0
import ssl
from stompest.config import StompConfig
from stompest.protocol import StompSpec
from stompest.sync import Stomp

context = ssl.create_default_context()
# Disable cert validation for demo only
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE

CONFIG = StompConfig('ssl://localhost:61612', sslContext=context)
QUEUE = '/queue/test'

if __name__ == '__main__':
    client = Stomp(CONFIG)
    client.connect()
    client.subscribe(QUEUE,
                     {StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL})
    while True:
        frame = client.receiveFrame()
        print('Got %s' % frame.info())
        client.ack(frame)
    client.disconnect()
示例#7
0
# -*- coding:utf-8 -*-
import logging
from stompest.config import StompConfig
from stompest.sync import Stomp

logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)

uri = 'failover:(tcp://x:61613,tcp://y:61613,tcp://z:61613)?randomize=false,startupMaxReconnectAttempts=3,initialReconnectDelay=7,maxReconnectDelay=8,maxReconnectAttempts=0'

CONFIG = StompConfig(uri)
QUEUE = '/queue/liuyang-test'

if __name__ == '__main__':
    client = Stomp(CONFIG)
    client.connect()
    client.send(QUEUE, 'test message 1')
    client.send(QUEUE, 'test message 2')
    client.disconnect()
示例#8
0
import logging
import unittest

from stompest.config import StompConfig
from stompest.error import StompConnectionError, StompProtocolError
from stompest.protocol import commands, StompFrame, StompSpec, StompSession
from stompest.sync import Stomp

from stompest.tests import mock

logging.basicConfig(level=logging.DEBUG)

HOST = 'fakeHost'
PORT = 61613

CONFIG = StompConfig('tcp://%s:%s' % (HOST, PORT), check=False)

class SimpleStompTest(unittest.TestCase):
    def _get_transport_mock(self, receive=None, config=None):
        stomp = Stomp(config or CONFIG)
        stomp._transport = mock.Mock()
        if receive:
            stomp._transport.receive.return_value = receive
        return stomp

    def _get_connect_mock(self, receive=None, config=None):
        stomp = Stomp(config or CONFIG)
        stomp._transportFactory = mock.Mock()
        transport = stomp._transportFactory.return_value = mock.Mock()
        transport.host = 'mock'
        transport.port = 0
示例#9
0
def get_stomp_client():
    conf = StompConfig(STOMP_SERVER,
                       login=STOMP_USERNAME,
                       passcode=STOMP_PASSWORD)  # , version='1.1')
    return Stomp(conf)
示例#10
0
import re
import traceback

from bs4 import BeautifulSoup
from stompest.config import StompConfig
from stompest.sync.client import Stomp

from Scheduler import settings
from common.MqSend import send_hebao_mq
from common.log import Logger
from common.mongodb.mongoUtils import mg_update_insert, mg_find
from common.redisUtil import CRedis
from request_ancheng.login import login_ancheng
from request_ancheng.request_data import query_hebao_data, query_hebao_reason

CONFIG = StompConfig(settings.i_config.MQHOST)
log = Logger()

r = CRedis()
appno_key = '12_APPNO'


def check_reason(session, appNo):
    ret = query_hebao_reason(session, appNo)

    baodan_trails_list = []

    if len(ret.text) > 300:
        ra = "DATA:\['(.*?)'\]"
        rb = re.compile(ra)
 def __init__(self):
   config = PropertyUtil(r"config.ini")
   config[RequestProcessor.CONFIG] = StompConfig(uri="failover:("+config.getAsString(RequestProcessor.URL)+")?startupMaxReconnectAttempts=-1,initialReconnectDelay=300000")
   self.CONFIG = config
示例#12
0
                   help='Queue name to move message to')
cliargs.add_option(
    '-c',
    '--close',
    dest='tmout',
    default=5,
    help='Amount of time in seconds to wait for a message before exiting')

(options, args) = cliargs.parse_args()

broker = options.broker
port = options.port
from_queue = options.from_queue
to_queue = options.to_queue
tmout = int(options.tmout)
config = StompConfig('tcp://{0}:{1}'.format(broker, port))
client = Stomp(config)

try:
    client.connect()
except stompest.error.StompConnectTimeout:
    print('Unable to connect to {0}:{1}'.format(broker, port))
    client.disconnect()
    sys.exit(1)
else:
    print('STOMP connection established to {0}:{1}'.format(broker, port))

client.subscribe(from_queue,
                 {StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL})

while client.canRead(timeout=tmout):
示例#13
0
 def run(self):
     client = Stomp(StompConfig('tcp://'+config['queue.host']+':'+str(config['queue.port'])+'?startupMaxReconnectAttempts=-1,initialReconnectDelay=1000,maxReconnectAttempts=-1'))
     yield client.connect()
     headers = { StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL }
     client.subscribe('/queue/Comets', headers, listener = SubscriptionListener(self.consume, errorDestination = '/queue/error'))
示例#14
0
    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,  # means 'latest available'
            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.last_heartbeat = 0
        self.ALLOWANCE = 2  # multiplier for heartbeat timeouts
示例#15
0
from resources import CollectorIdResource
from config import AppConfig

# Third-party Imports
from stompest.config import StompConfig
from stompest.sync import Stomp

# import os
import falcon
import bjoern

###########################################
# ActiveMQ Stomp Connection Configuration #
###########################################
stompconf = StompConfig('tcp://{}:{}'.format(AppConfig.ACTIVEMQ['host'],
                                             AppConfig.ACTIVEMQ['port']),
                        version=AppConfig.ACTIVEMQ['stomp_version'])

############################
# Falcon API Configuration #
############################

# Middleware Configuration
api = falcon.API(middleware=[ActiveMQSession(stompconf)])

# Route Configuration
api.add_route('/collector/{queue}', CollectorIdResource())

# Serve application
if __name__ == '__main__':
                                                   toks[1])
                            if namespace.queue == processor_class.get_input_queue_name(
                            ):
                                # Instantiate and call the processor
                                proc = processor_class(data,
                                                       configuration,
                                                       send_function=pp.send)
                                proc()
                        except:
                            logging.error(
                                "PostProcessAdmin: Processor error: %s" %
                                sys.exc_value)
                    else:
                        logging.error(
                            "PostProcessAdmin: Processors can only be specified in the format module.Processor_class"
                        )

        except:
            # If we have a proper data dictionary, send it back with an error message
            if type(data) == dict:
                data["error"] = str(sys.exc_value)
                stomp = Stomp(
                    StompConfig(configuration.failover_uri,
                                configuration.amq_user, configuration.amq_pwd))
                stomp.connect()
                stomp.send(configuration.postprocess_error, json.dumps(data))
                stomp.disconnect()
            raise
    except:
        logging.error("PostProcessAdmin: %s" % sys.exc_value)
示例#17
0
 def __init__(self, config=None):
     if config is None:
         config = StompConfig('tcp://127.0.0.1:61613')
         # config = StompConfig('tcp://52.80.31.10:61613')
     self.config = config
示例#18
0
 def test_connect_raises_exception_for_bad_host(self):
     stomp = Stomp(StompConfig('tcp://nosuchhost:2345'))
     self.assertRaises(Exception, stomp.connect)
示例#19
0
 def __init__(self, config=None):
     if config is None:
         config = StompConfig(default_uri)
     else:
         config = StompConfig(config)
     self.config = config
示例#20
0
#!/usr/bin/python

import logging, sys
import time
from stompest.config import StompConfig
from stompest.sync import Stomp

logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)

CONFIG = StompConfig('tcp://localhost:7777', version='1.2')


def toTime(input):
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(input))

if __name__ == '__main__':

    client = Stomp(CONFIG)

    client.connect(connectedTimeout=4, heartBeats=(1000,0))

    print "--------------------------------------------------------------------"
    print "state        : ", client.session.state
    print "client HB    : ", client.session.clientHeartBeat
    print "server HB    : ", client.session.serverHeartBeat
    print "server       : ", client.session.server
    print "id           : ", client.session.id
    print "lastSent     : ", toTime(client.session.lastSent)
    print "lastReceived : ", toTime(client.session.lastReceived)
    
    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,  # means 'latest available'
            key_file_password=None,
            proxy_host=None,
            proxy_port=None,
            proxy_user=None,
            proxy_password=None,
            channel=channel,
            stomp_params=None):
        """ 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 based on settings
        # build any parameters passed
        # every connection has at least these two: maxReconnectAttempts, startupMaxReconnectAttempts
        items = [item.split("=", 2)
                 for item in stomp_params.split(",")] if stomp_params else None
        connection_params = {
            item[0].strip(): item[1].strip()
            for item in items
        } if items else {}

        if "maxReconnectAttempts" not in connection_params:
            connection_params[
                'maxReconnectAttempts'] = DEFAULT_MAX_RECONNECT_ATTEMPTS
        if "startupMaxReconnectAttempts" not in connection_params:
            connection_params[
                'startupMaxReconnectAttempts'] = DEFAULT_STARTUP_MAX_RECONNECT_ATTEMPTS

        self._stomp_server = "failover:({0})?{1}".format(
            uri, ",".join(
                ["{}={}".format(k, v) for k, v in connection_params.items()]))
        LOG.debug("Stomp uri: {}".format(self._stomp_server))

        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.last_heartbeat = 0
        self.ALLOWANCE = 2  # multiplier for heartbeat timeouts
 def getConfig(self, version, port=None):
     return StompConfig('tcp://%s:%s' % (HOST, port or PORT), login=LOGIN, passcode=PASSCODE, version=version)
示例#23
0
'''
@author: Saravana Perumal Shanmugam
'''

from stompest.config import StompConfig
from stompest.protocol import StompSpec
from stompest.sync import Stomp
import logging

CONFIG = StompConfig('tcp://localhost:61613', version=StompSpec.VERSION_1_0)
QUEUE = 'jms.queue.prodcons'

if __name__ == '__main__':
    logging.basicConfig()
    logging.getLogger().setLevel(logging.DEBUG)
    client = Stomp(CONFIG)
    client.connect()
    client.subscribe(QUEUE,
                     {StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL})
    while True:
        frame = client.receiveFrame()
        print 'Got %s' % frame.body
        client.ack(frame)
        if frame.body == 'done':
            break
    client.disconnect()
示例#24
0
 def __init__(self, config=None):
     if config is None:
         config = StompConfig('tcp://localhost:61613')
     self.config = config
示例#25
0
import unittest

from mock import Mock

from stompest.config import StompConfig
from stompest.error import StompConnectionError, StompProtocolError
from stompest.protocol import commands, StompFrame, StompSpec
from stompest.sync import Stomp

logging.basicConfig(level=logging.DEBUG)

HOST = 'fakeHost'
PORT_TCP = 61613
PORT_SSL = 61612

CONFIG_TCP = StompConfig('tcp://%s:%s' % (HOST, PORT_TCP), check=False)
CONFIG_SSL = StompConfig('ssl://%s:%s' % (HOST, PORT_TCP), check=False)


class SimpleStompTest(unittest.TestCase):
    def _get_transport_mock(self, receive=None, config=None):
        stomp = Stomp(config or CONFIG_TCP)
        stomp._transport = Mock()
        if receive:
            stomp._transport.receive.return_value = receive
        return stomp

    def _get_connect_mock(self, receive=None, config=None):
        stomp = Stomp(config or CONFIG_TCP)
        stomp._transportFactory = Mock()
        transport = stomp._transportFactory.return_value = Mock()
示例#26
0
import os
import sys
import time

from stompest.config import StompConfig
from stompest.sync import Stomp

user = os.getenv('APOLLO_USER') or 'admin'
password = os.getenv('APOLLO_PASSWORD') or 'password'
host = os.getenv('APOLLO_HOST') or 'localhost'
port = int(os.getenv('APOLLO_PORT') or 61613)
destination = sys.argv[1:2] or ['/topic/event']
destination = destination[0]

config = StompConfig('tcp://%s:%d' % (host, port),
                     login=user,
                     passcode=password,
                     version='1.1')
client = Stomp(config)

client.connect(host='mybroker')
client.subscribe(destination=destination,
                 headers={'id': 'required-for-STOMP-1.1'})

count = 0
start = time.time()

while (not count) or client.canRead(0):
    client.receiveFrame()
    count += 1

diff = time.time() - start
示例#27
0
import ssl
from stompest.config import StompConfig
from stompest.protocol import StompSpec
from stompest.sync import Stomp

context = ssl.create_default_context()
# Disable cert validation for demo only
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE

CONFIG = StompConfig(uri='ssl://x.x.x.x:61614',
                     login='******',
                     passcode='password',
                     check=False,
                     sslContext=context)
QUEUE = '/queue/my-queue'
RQUEUE = '/queue/my-reply'

if __name__ == '__main__':
    client = Stomp(CONFIG)
    client.connect()
    client.subscribe(QUEUE,
                     {StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL})
    frame = client.receiveFrame()
    print('Got %s' % frame.info())
    client.ack(frame)
    client.send(RQUEUE, b'hello', headers={'correlation-id': 0})
    client.disconnect()