-
Notifications
You must be signed in to change notification settings - Fork 224
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[ISSUE #889] Python Example: start a simple consumer in background th…
…read (#889)
- Loading branch information
Showing
1 changed file
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
# Licensed to the Apache Software Foundation (ASF) under one or more | ||
# contributor license agreements. See the NOTICE file distributed with | ||
# this work for additional information regarding copyright ownership. | ||
# The ASF licenses this file to You under the Apache License, Version 2.0 | ||
# (the "License"); you may not use this file except in compliance with | ||
# the License. You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
from rocketmq import ClientConfiguration, Credentials, SimpleConsumer | ||
import asyncio | ||
import threading | ||
|
||
|
||
def start_simple_consumer(): | ||
endpoints = "endpoints" | ||
credentials = Credentials("ak", "sk") | ||
config = ClientConfiguration(endpoints, credentials) | ||
topic = "topic" | ||
try: | ||
simple_consumer = SimpleConsumer(config, "consumer-group") | ||
simple_consumer.startup() | ||
simple_consumer.subscribe(topic) | ||
while True: | ||
try: | ||
messages = simple_consumer.receive(32, 15) | ||
if messages is not None: | ||
print(f"{simple_consumer.__str__()} receive {len(messages)} messages.") | ||
for msg in messages: | ||
simple_consumer.ack(msg) | ||
print(f"{simple_consumer.__str__()} ack message:[{msg.message_id}].") | ||
except Exception as e: | ||
print(f"receive or ack message raise exception: {e}") | ||
except Exception as e: | ||
print(f"simple consumer example raise exception: {e}") | ||
|
||
|
||
def run_simple_consumer(): | ||
loop = asyncio.new_event_loop() | ||
asyncio.set_event_loop(loop) | ||
loop.run_until_complete(start_simple_consumer()) | ||
|
||
|
||
if __name__ == '__main__': | ||
# start a simple consumer in background thread | ||
t = threading.Thread(target=run_simple_consumer) | ||
t.start() | ||
print("start background simple consumer success!") | ||
t.join() |