-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
61 lines (45 loc) · 1.85 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import asyncio
import os
import sys
import logging
import aio_pika
from tsp_solver.dispatcher import Dispatcher
# Configure logging settings
logging.basicConfig(filename='tsp_solver.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s')
async def start_service(consumer_class) -> None:
# Creat connection
connection = await aio_pika.connect_robust(
url="amqp://{}:{}@{}/".format(os.environ.get('MESSAGE_BROKER_USERNAME', 'admin'),
os.environ.get('MESSAGE_BROKER_PASSWORD', 'admin'),
os.environ.get('MESSAGE_BROKER', 'localhost'))
)
input_queue_name = os.environ.get('TSP_INPUT_QUEUE', 'TSP_INPUT_QUEUE')
output_queue_name = os.environ.get('TSP_OUTPUT_QUEUE', 'TSP_OUTPUT_QUEUE')
try:
async with connection:
# Creating channel
channel = await connection.channel()
# Will take no more than 10 messages in advance
await channel.set_qos(prefetch_count=10)
# Declaring queue
input_queue = await channel.declare_queue(input_queue_name, auto_delete=False)
output_queue = await channel.declare_queue(output_queue_name)
# Setup consumer
consumer = consumer_class(channel=channel, queue=input_queue, )
await consumer.consume()
finally:
await connection.close()
def main():
logging.info('TSP solver service is going to be started.')
try:
asyncio.run(start_service(Dispatcher))
except asyncio.CancelledError:
logging.info('Main task cancelled')
except Exception as e:
logging.exception('Something unexpected happened: ', e)
finally:
logging.info("Shutdown complete")
if __name__ == '__main__':
sys.exit(main())
# Shutdown the logger when done
logging.shutdown()