-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path08_eventbus_basic.py
More file actions
68 lines (51 loc) · 1.65 KB
/
08_eventbus_basic.py
File metadata and controls
68 lines (51 loc) · 1.65 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""Basic EventBus Usage
Demonstrates:
- Creating EventBus with process and app brokers
- Direct subscription and publishing
- Basic event handling with PROCESS scope
"""
import asyncio
import logging
from opensecflow.eventbus.memory_broker import AsyncQueueBroker
from opensecflow.eventbus.eventbus import EventBus
from opensecflow.eventbus.event import ScopedEvent, EventScope
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
async def main():
"""Basic EventBus publish-subscribe example"""
print("\n=== Basic EventBus Usage ===\n")
# Create two brokers
process_broker = AsyncQueueBroker()
app_broker = AsyncQueueBroker()
# Create EventBus
bus = EventBus(process_broker, app_broker)
# Define event class
class OrderCreatedEvent(ScopedEvent):
type: str = "order.created"
order_id: str
amount: float
scope: EventScope = EventScope.PROCESS
# Define handler function
async def handle_order(event_data: dict):
print(f" 📦 Received order: ID={event_data.get('order_id')}, Amount={event_data.get('amount')}")
# Subscribe to event
bus.subscribe("order.created", handle_order)
# Start EventBus
await bus.start()
# Publish event
print(" Publishing order event...")
event = OrderCreatedEvent(
source="order-service",
order_id="ORD-001",
amount=99.9
)
await bus.publish(event)
# Wait for event processing
await asyncio.sleep(0.5)
print(" Event processing complete")
await bus.stop()
if __name__ == "__main__":
asyncio.run(main())