本文整理汇总了Python中stompest.sync.Stomp类的典型用法代码示例。如果您正苦于以下问题:Python Stomp类的具体用法?Python Stomp怎么用?Python Stomp使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Stomp类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-d", nargs=1, required=True, help="destination", metavar="dest")
parser.add_argument("-e", action="store_true", default=False, help="persistent msgs flag")
parser.add_argument("-m", nargs=1, required=True, help="msg", metavar="msg")
parser.add_argument("-n", nargs=1, default=False, help="number of msgs", metavar="int")
parser.add_argument("-p", nargs=1, default=False, help="msg prefix", metavar="msg prefix")
parser.add_argument("-s", nargs=1, required=True, help="broker", metavar="broker")
parser.add_argument("-t", nargs=1, default=False, help="send msg every sec", metavar="float")
args = parser.parse_args()
broker = "tcp://%s:6163" % (args.s[0])
config = StompConfig(broker)
client = Stomp(config)
client.connect()
rd = "".join(random.sample("abcdefghijklmno", 2))
try:
i = 0
if args.n:
while i < int(args.n[0]):
send_msg(args, client, i, rd)
i += 1
else:
while True:
send_msg(args, client, i, rd)
i += 1
except KeyboardInterrupt:
client.disconnect()
raise SystemExit(1)
示例2: call_route
def call_route(request_queue, response_queue, request):
"""
"""
config = {
"stomp": {
"server": '192.168.0.3',
"port": 61613,
"timeout": 15,
}
}
stomp_config = StompConfig("tcp://%s:%d" % (config['stomp']['server'], config['stomp']['port']), version=StompSpec.VERSION_1_0)
stomp = Stomp(stomp_config)
stomp.connect()
jms_id = str(uuid4())
token = stomp.subscribe(response_queue, {'JMSCorrelationID': jms_id})
stomp.send(request_queue, json.dumps(request), {'JMSCorrelationID': jms_id})
response = None
if stomp.canRead(config['stomp']['timeout']):
response = stomp.receiveFrame()
stomp.unsubscribe(token)
return response
示例3: _get_timeouting_connect_mock
def _get_timeouting_connect_mock(self):
stomp = Stomp(CONFIG)
stomp._transportFactory = mock.Mock()
transport = stomp._transportFactory.return_value = mock.Mock()
transport.host = 'mock'
transport.port = 0
transport.canRead.return_value = False
return stomp
示例4: configureClient
def configureClient(self, _login, _passcode):
CONFIG = StompConfig("tcp://datafeeds.networkrail.co.uk:61618", login=_login, passcode=_passcode)
client = Stomp(CONFIG)
client.connect()
client.subscribe("/topic/TD_KENT_MCC_SIG_AREA")
self._client = client
示例5: _get_connect_mock
def _get_connect_mock(self, receive=None, config=None):
stomp = Stomp(config or CONFIG)
stomp._transportFactory = Mock()
transport = stomp._transportFactory.return_value = Mock()
transport.host = 'mock'
transport.port = 0
if receive:
transport.receive.return_value = receive
return stomp
示例6: recv_stomp
def recv_stomp ():
config = StompConfig (stomp_uri)
client = Stomp (config)
client.connect ()
client.subscribe (stomp_source, {StompSpec.ACK_HEADER: StompSpec.ACK_CLIENT_INDIVIDUAL})
frame = client.receiveFrame ()
print "Received: {}".format (frame.info ())
client.ack (frame)
client.disconnect ()
示例7: _conn
def _conn(cfg_uri, queue, _info):
from stompest.config import StompConfig
from stompest.sync import Stomp
_info("Init Stomp obj: [%s-%s]" % (cfg_uri, queue))
client = Stomp(StompConfig(cfg_uri))
_info("connecting... %s" % cfg_uri)
client.connect()
_info("connected %s" % cfg_uri)
return client
示例8: __init__
def __init__(self, config):
"""Init the Stompest wrapper client.
:type config: dict
:param config: The configuration for the STOM client.
I.e. {'host': 'tcp://127.0.0.1',
'queue': '/queue/test',
'transaction': True,
'username': 'my_username',
'password': 'fido5'}
The transaction attribute defines if messages should be published
in transactions.
"""
self.host = config['host']
self.queue = config['queue']
self.transactions_enabled = config['transaction']
self.transaction = None
auth_header = {}
if 'username' in config and 'password' in config:
auth_header.update(
{StompSpec.LOGIN_HEADER: config['username'],
StompSpec.PASSCODE_HEADER: config['password']})
self.client = Stomp(StompConfig(self.host))
try:
self.client.connect(headers=auth_header)
except (error.StompConnectTimeout, error.StompProtocolError) as e:
raise ClientErrors.ConnectionError(
"Could not connect to broker: %s" % e)
示例9: init
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
示例10: writeJson
def writeJson(value,*argv):
'''Writes the specified value to an output file
Takes:
value-> List or Dict
*argv: Available options:
'stomp'
'post'
'outfile'
Returns:
none
'''
outJson=json.dumps(value)
print outJson
if 'stomp' in argv:
CONFIG = StompConfig(stomp_config.server, stomp_config.login,stomp_config.passcode)
QUEUE = stomp_config.queue
client = Stomp(CONFIG)
client.connect()
client.send(QUEUE, outJson)
client.disconnect()
elif 'outfile' in argv:
with open(outfile,'w') as jsonFile:
jsonFile.write(outJson)
elif 'post' in argv:
#TODO Post to php server
pass
示例11: connect
def connect(self, host, port=61613, user=None, passw=None, timeout=10):
"""Method connects to server
Args:
host (str): hostname
port (str): port
user (str): username
passw (str): password
timeout (int): timeout
Returns:
bool: result
Raises:
event: jms_before_connect
event: jms_after_connected
"""
try:
msg = 'host:{0}, port:{1}, user:{2}, passw:{3}, timeout:{4}'.format(
host, port, user, passw, timeout)
self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
'htk_jms_connecting', msg), self._mh.fromhere())
ev = event.Event(
'jms_before_connect', host, port, user, passw, timeout)
if (self._mh.fire_event(ev) > 0):
host = ev.argv(0)
port = ev.argv(1)
user = ev.argv(2)
passw = ev.argv(3)
timeout = ev.argv(4)
self._host = host
self._port = port
self._user = user
self._passw = passw
if (ev.will_run_default()):
self._client = Stomp(StompConfig('tcp://{0}:{1}'.format(self._host, self._port),
login=self._user, passcode=self._passw))
self._client.connect(
connectTimeout=timeout, connectedTimeout=timeout)
self._is_connected = True
self._mh.demsg('htk_on_debug_info', self._mh._trn.msg(
'htk_jms_connected'), self._mh.fromhere())
ev = event.Event('jms_after_connect')
self._mh.fire_event(ev)
return True
except StompError as ex:
self._mh.demsg('htk_on_error', ex, self._mh.fromhere())
return False
示例12: main
def main():
parser = argparse.ArgumentParser()
parser.add_argument('config_file')
parser.add_argument('--debug', action='store_true')
parser.add_argument('--logfile')
parser.add_argument('--purge', action='store_true')
parser.add_argument('--loadgen', action='store_true')
parser.add_argument('--sessionid')
parser.add_argument('--httpserver', action='store_true')
args = parser.parse_args()
if args.logfile:
fh = FileHandler(args.logfile)
formatter = logging.Formatter(FORMAT)
fh.setFormatter(formatter)
logger.addHandler(fh)
if args.debug:
logger.setLevel(logging.DEBUG)
config = yaml.load(open(args.config_file))
sessionmaker = config_to_db_session(config, Base)
stomp_endpoint = config['stomp_endpoint']
stomp_login = config['stomp_login']
stomp_password = config['stomp_password']
stomp_config = StompConfig(stomp_endpoint, login=stomp_login, passcode=stomp_password)
if args.purge:
purge_completed_jobs(sessionmaker())
return
elif args.loadgen:
if not args.sessionid:
raise ValueError('parameter sessionid is required for load generator')
jm = StompSync(stomp_config)
jm.connect()
generate_load(jm, args.sessionid)
jm.disconnect()
return
elif args.httpserver:
from jobmanager.www import app
app.config['DB'] = sessionmaker
app.config['params'] = config
app.run()
return
jm = JobManager(sessionmaker, config=stomp_config)
jm.run()
l = task.LoopingCall(jm.run_periodic_checks)
l.start(PERIODIC_CHECK_INTERVAL)
reactor.run()
示例13: main
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-d', nargs=1, required=True, help='destination', metavar='dest')
parser.add_argument('-e', action='store_true', default=False, help='persistent msgs flag')
parser.add_argument('-a', nargs=1, required=False, help='fixed timestamp', metavar='fixed timestamp')
parser.add_argument('-n', nargs=1, default=False, help='number of msgs', metavar='int')
parser.add_argument('-o', default=6163, type=int, help='port', metavar='port')
parser.add_argument('-z', default=16, type=int, help='size of msg payload', metavar='msg prefix')
parser.add_argument('-p', nargs=1, default=False, help='msg prefix', metavar='msg prefix')
parser.add_argument('-s', nargs=1, required=True, help='broker', metavar='broker')
parser.add_argument('-i', action='store_true', required=False, default=False, help='paired service type')
parser.add_argument('-w', action='store_true', default=False, help='format message wrongly')
parser.add_argument('-t', nargs=1, default=False, help='send msg every sec', metavar='float')
parser.add_argument('-v', action='store_true', default=False, help='verbose')
args = parser.parse_args()
broker = 'tcp://%s:%i' % (args.s[0], args.o)
config = StompConfig(broker)
client = Stomp(config)
client.connect()
try:
i = 0
if args.n:
while i < int(args.n[0]):
msg = gen_msg(args)
if args.v:
print str(i)
print '%.128s' % msg
send_msg(args, client, msg)
i += 1
else:
while True:
msg = gen_msg(args)
if args.v:
print str(i)
print '%.128s' % msg
send_msg(args, client, msg)
i += 1
except KeyboardInterrupt:
client.disconnect()
raise SystemExit(1)
示例14: test_3_timeout
def test_3_timeout(self):
timeout = 0.2
client = Stomp(StompConfig(uri='failover:(tcp://localhost:61610,tcp://localhost:61613)?startupMaxReconnectAttempts=1,randomize=false', login=LOGIN, passcode=PASSCODE, version=StompSpec.VERSION_1_0))
client.connect(host=VIRTUALHOST, connectTimeout=timeout)
client.disconnect()
client = Stomp(StompConfig(uri='failover:(tcp://localhost:61610,tcp://localhost:61611)?startupMaxReconnectAttempts=1,backOffMultiplier=3', login=LOGIN, passcode=PASSCODE, version=StompSpec.VERSION_1_0))
self.assertRaises(StompConnectionError, client.connect, host=VIRTUALHOST, connectTimeout=timeout)
client = Stomp(StompConfig(uri='failover:(tcp://localhost:61610,tcp://localhost:61613)?randomize=false', login=LOGIN, passcode=PASSCODE, version=StompSpec.VERSION_1_0)) # default is startupMaxReconnectAttempts = 0
self.assertRaises(StompConnectionError, client.connect, host=VIRTUALHOST, connectTimeout=timeout)
示例15: __init__
def __init__(self, namespace, login, passcode, broker_host=DEFAULT_BROKER_HOST, device_uid=None, channel_type='topic'):
'''
Create a ByteportStompClient. This is a thin wrapper to the underlying STOMP-client that connets to the Byteport Broker
If a device_uid is given, a subscription will be made for Messages sent through Byteport.
The channel_type must be either 'topic' or 'queue'. Set top topic if unsure on what to use (use queue if you need to
use multiple consumers for a single device, this is not how most applications are set up).
:param namespace:
:param login: Broker username (Byteport web users are _not_ valid broker users). Ask [email protected] for access.
:param passcode: Broker passcode
:param broker_hosts: [optional] A list of brokers to connect to
:param device_uid: [optional] The device UID to subscribe for messages on
:param channel_type: [optional] Defaults to queue.
:param channel_key: [optional] Must match the configured key in the Byteport Device Manager
'''
self.namespace = str(namespace)
self.device_uid = device_uid
if channel_type not in self.SUPPORTED_CHANNEL_TYPES:
raise Exception("Unsupported channel type: %s" % channel_type)
broker_url = 'tcp://%s:61613' % broker_host
self.CONFIG = StompConfig(broker_url, version=StompSpec.VERSION_1_2)
self.client = Stomp(self.CONFIG)
try:
self.client.connect(headers={'login': login, 'passcode': passcode}, host='/')
logging.info("Connected to Stomp broker at %s using protocol version %s" % (broker_host, self.client.session.version))
# Set up a subscription on the correct queue if a Specific device UID was given
if self.device_uid:
subscribe_headers = dict()
subscribe_headers[StompSpec.ACK_HEADER] = StompSpec.ACK_CLIENT_INDIVIDUAL
subscribe_headers[StompSpec.ID_HEADER] = '0'
device_message_queue_name = '/%s/device_messages_%s.%s' % (channel_type, namespace, device_uid)
self.subscription_token = self.client.subscribe(device_message_queue_name, subscribe_headers)
logging.info("Subscribing to channel %s" % device_message_queue_name)
except StompProtocolError as e:
logging.error("Client socket connected, but probably failed to login. (ProtocolError)")
raise
except StompConnectionError:
logging.error("Failed to connect to Stomp Broker at %s" % broker_host)
raise