-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.py
More file actions
50 lines (44 loc) · 1.51 KB
/
Copy pathworker.py
File metadata and controls
50 lines (44 loc) · 1.51 KB
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
import json
import logging
import time
import pika
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.propagate import extract
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(__name__)
# OpenTelemetry
resource = Resource.create({"service.name": "worker"})
provider = TracerProvider(resource=resource)
otlp_exporter = OTLPSpanExporter()
processor = BatchSpanProcessor(otlp_exporter)
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)
tracer = trace.get_tracer(__name__)
# RabbitMQ
RABBITMQ_HOST = "rabbitmq"
QUEUE_NAME = "my_queue"
connection = pika.BlockingConnection(
pika.ConnectionParameters(RABBITMQ_HOST, heartbeat=3600)
)
channel = connection.channel()
def callback(ch, method, properties, body):
headers = properties.headers or {}
ctx = extract(headers)
with tracer.start_span(
"consume_message", context=ctx, kind=trace.SpanKind.CONSUMER
):
sleep = json.loads(body)["sleep"]
logger.warning("Sleeping for %ss", sleep)
time.sleep(sleep)
ch.basic_ack(delivery_tag=method.delivery_tag)
channel.queue_declare(queue=QUEUE_NAME, durable=True)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(
queue=QUEUE_NAME,
on_message_callback=callback
)
channel.start_consuming()