本文整理汇总了Python中stompest.sync.Stomp类的典型用法代码示例。如果您正苦于以下问题:Python Stomp类的具体用法?Python Stomp怎么用?Python Stomp使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Stomp类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:vrdel,项目名称:brokers-test,代码行数:31,代码来源:producer.py
示例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
开发者ID:siwells,项目名称:sandpit,代码行数:25,代码来源:stomptest.py
示例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
开发者ID:nikipore,项目名称:stompest,代码行数:8,代码来源:sync_client_test.py
示例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
开发者ID:sparky18,项目名称:networkrail,代码行数:8,代码来源:watch.py
示例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
开发者ID:irdetoakinavci,项目名称:AMQMessageProducer,代码行数:9,代码来源:sync_client_test.py
示例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 ()
开发者ID:jpbarto,项目名称:stomp_eval,代码行数:9,代码来源:stompest-test.py
示例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
开发者ID:yankaics,项目名称:xtls,代码行数:10,代码来源:mqwrapper.py
示例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)
开发者ID:unioslo,项目名称:cerebrum,代码行数:30,代码来源:stomp_client.py
示例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
开发者ID:spaceone,项目名称:circuits,代码行数:59,代码来源:client.py
示例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
开发者ID:5inister,项目名称:onlines,代码行数:26,代码来源:controls.py
示例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
开发者ID:hydratk,项目名称:hydratk-lib-network,代码行数:57,代码来源:stomp_client.py
示例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()
开发者ID:CSC-IT-Center-for-Science,项目名称:chipster-job-manager,代码行数:54,代码来源:manager.py
示例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)
开发者ID:vrdel,项目名称:brokers-test,代码行数:42,代码来源:producer-argo.py
示例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)
开发者ID:nikipore,项目名称:stompest,代码行数:11,代码来源:sync_client_integration_test.py
示例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
开发者ID:gebart,项目名称:byteport-api,代码行数:50,代码来源:stomp_client.py
示例16: connect_to_amq
def connect_to_amq(tb, queue=False, topic=False):
# Format the connection url
dl_ff_ip, dl_north_rest = tb.dl_northside_rest.split(":")
dl_activemq_stomp_port = 61613
url = "tcp://{}:{}".format(dl_ff_ip, dl_activemq_stomp_port)
# Create stomp config
config = StompConfig(url)
stomp = Stomp(config)
# Connect to activemq
stomp.connect()
if queue:
stomp.subscribe(queue, {StompSpec.ID_HEADER: u'testbench'})
elif topic:
stomp.subscribe('/topic/' + str(topic), {StompSpec.ID_HEADER: u'testbench'})
# return the stomp
return stomp
开发者ID:suryatejah,项目名称:testing,代码行数:16,代码来源:test_demo.py
示例17: connect
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)
开发者ID:dantman,项目名称:gareth,代码行数:19,代码来源:messagebroker.py
示例18: run
def run(self):
files = os.listdir(self.path)
for queue_file in files:
archive_file = '{0}/archive/{1}'.format(self.path, queue_file)
if queue_file.startswith('archive'):
pass
else:
with open("{0}/{1}".format(self.path, queue_file), 'r') as qf:
get_lines = list(qf)
for line in get_lines:
dts = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
client = Stomp(config=self.config)
client.connect()
print "Sending message {0} to queue {1}".format(line, queue_file)
with open(archive_file, 'a') as af:
af.write("{0} Sent message: {1} to queue {2}\n".format(dts, line, queue_file))
client.send(queue_file, json.dumps(line))
client.disconnect()
开发者ID:saxrussell,项目名称:activemq_tools,代码行数:18,代码来源:doomsday_recovery.py
示例19: send_message
def send_message(messageBody, destination=None, queueName=None):
client = None
if destination != None:
client = Stomp(StompConfig(destination))
else:
client = Stomp(StompConfig("tcp://localhost:61613"))
QUEUE = None
if queueName != None:
QUEUE = queueName
else:
QUEUE = "pods2jbpm"
#client = Stomp(CONFIG)
client.connect()
body = messageBody
client.send(QUEUE, body)
client.disconnect()
开发者ID:irdetoakinavci,项目名称:AMQMessageProducer,代码行数:22,代码来源:messageProducer.py
示例20: send
def send(self):
"""
Create a new stomp configuration client, connect and
then serializes message by message posting
them to your consumers in TOPIC standard
and disconnect.
"""
try:
configuration = StompConfig(uri=self._broker_uri)
client = Stomp(configuration)
client.connect(connectTimeout=self._broker_timeout)
for message in self._queue:
serialized_message = json.dumps(message, ensure_ascii=False)
client.send(self._queue_destination, serialized_message)
client.disconnect()
except Exception, e:
self.log.error(u"QueueManagerError - Error on sending objects from queue.")
self.log.debug(e)
开发者ID:andrewsmedina,项目名称:GloboNetworkAPI,代码行数:24,代码来源:queue_manager.py
注:本文中的stompest.sync.Stomp类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论