Debian Codegraph @

examples/quorum-queues/myapp.py

raw
1 """myapp.py
2
3 Usage::
4
5 (window1)$ python myapp.py worker -l INFO
6
7 (window2)$ celery shell
8 >>> from myapp import example
9 >>> example()
10
11
12 You can also specify the app to use with the `celery` command,
13 using the `-A` / `--app` option::
14
15 $ celery -A myapp worker -l INFO
16
17 With the `-A myproj` argument the program will search for an app
18 instance in the module ``myproj``. You can also specify an explicit
19 name using the fully qualified form::
20
21 $ celery -A myapp:app worker -l INFO
22
23 """
24
25 import os
26 from datetime import UTC, datetime, timedelta
27
28 from declare_queue import my_quorum_queue
29
30 from celery import Celery
31 from celery.canvas import group
32
33 app = Celery("myapp", broker="amqp://guest@localhost//")
34
35 # Use custom queue (Optional) or set the default queue type to "quorum"
36 # app.conf.task_queues = (my_quorum_queue,) # uncomment to use custom queue
37 app.conf.task_default_queue_type = "quorum" # comment to use classic queue
38
39 # Required by Quorum Queues: https://www.rabbitmq.com/docs/quorum-queues#use-cases
40 app.conf.broker_transport_options = {"confirm_publish": True}
41
42 # Reduce qos to 4 (Optional, useful for testing)
43 app.conf.worker_prefetch_multiplier = 1
44 app.conf.worker_concurrency = 4
45
46 # Reduce logs (Optional, useful for testing)
47 app.conf.worker_heartbeat = None
48 app.conf.broker_heartbeat = 0
49
50
51 def is_using_quorum_queues(app) -> bool:
52 queues = app.amqp.queues
53 for qname in queues:
54 qarguments = queues[qname].queue_arguments or {}
55 if qarguments.get("x-queue-type") == "quorum":
56 return True
57
58 return False
59
60
61 @app.task
62 def add(x, y):
63 return x + y
64
65
66 @app.task
67 def identity(x):
68 return x
69
70
71 def example():
72 queue = my_quorum_queue.name if my_quorum_queue in (app.conf.task_queues or {}) else "celery"
73
74 while True:
75 print("Celery Quorum Queue Example")
76 print("===========================")
77 print("1. Send a simple identity task")
78 print("1.1 Send an ETA identity task")
79 print("2. Send a group of add tasks")
80 print("3. Inspect the active queues")
81 print("4. Shutdown Celery worker")
82 print("Q. Quit")
83 print("Q! Exit")
84 choice = input("Enter your choice (1-4 or Q): ")
85
86 if choice == "1" or choice == "1.1":
87 queue_type = "Quorum" if is_using_quorum_queues(app) else "Classic"
88 payload = f"Hello, {queue_type} Queue!"
89 eta = datetime.now(UTC) + timedelta(seconds=30)
90 if choice == "1.1":
91 result = identity.si(payload).apply_async(queue=queue, eta=eta)
92 else:
93 result = identity.si(payload).apply_async(queue=queue)
94 print()
95 print(f"Task sent with ID: {result.id}")
96 print("Task type: identity")
97
98 if choice == "1.1":
99 print(f"ETA: {eta}")
100
101 print(f"Payload: {payload}")
102
103 elif choice == "2":
104 tasks = [
105 (1, 2),
106 (3, 4),
107 (5, 6),
108 ]
109 result = group(
110 add.s(*tasks[0]),
111 add.s(*tasks[1]),
112 add.s(*tasks[2]),
113 ).apply_async(queue=queue)
114 print()
115 print("Group of tasks sent.")
116 print(f"Group result ID: {result.id}")
117 for i, task_args in enumerate(tasks, 1):
118 print(f"Task {i} type: add")
119 print(f"Payload: {task_args}")
120
121 elif choice == "3":
122 active_queues = app.control.inspect().active_queues()
123 print()
124 print("Active queues:")
125 for worker, queues in active_queues.items():
126 print(f"Worker: {worker}")
127 for q in queues:
128 print(f" - {q['name']}")
129
130 elif choice == "4":
131 print("Shutting down Celery worker...")
132 app.control.shutdown()
133
134 elif choice.lower() == "q":
135 print("Quitting test()")
136 break
137
138 elif choice.lower() == "q!":
139 print("Exiting...")
140 os.abort()
141
142 else:
143 print("Invalid choice. Please enter a number between 1 and 4 or Q to quit.")
144
145 print("\n" + "#" * 80 + "\n")
146
147
148 if __name__ == "__main__":
149 app.start()