Skip to content

Commit

Permalink
chore: update
Browse files Browse the repository at this point in the history
  • Loading branch information
hhstore committed Jul 5, 2024
1 parent 9f2e05f commit 5a9fcab
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 0 deletions.
4 changes: 4 additions & 0 deletions packages/try-nats/py/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ pip install nats-py

```

### 说明:

- ✅ 给出了`多个 worker`, `唯一性`消费的示例, 非常简单.

### Nats 官方示例:

- https://github.com/nats-io/nats.py/tree/main/examples
Expand Down
6 changes: 6 additions & 0 deletions packages/try-nats/py/Taskfile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,9 @@ tasks:
cmds:
- python run_sub.py
dir: ./src/try_nats

sub:m:
aliases: [ "multi:sub", "m:sub" ]
cmds:
- python run_multi_sub.py
dir: ./src/try_nats
30 changes: 30 additions & 0 deletions packages/try-nats/py/src/try_nats/run_multi_sub.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import asyncio

from nats.aio.client import Client as NATS


async def message_handler(msg):
subject = msg.subject
data = msg.data.decode()
print(f"Received a message on '{subject}': {data}")


async def main():
nc = NATS()

await nc.connect("nats://localhost:4222")

#
# todo x: 基于 queue 方式订阅, worker 消息处理唯一性
#
await nc.subscribe("updates", "workers", cb=message_handler)

print("Listening for messages...")

# Keep the program running to listen for messages
while True:
await asyncio.sleep(1)


if __name__ == '__main__':
asyncio.run(main())
6 changes: 6 additions & 0 deletions packages/try-nats/py/src/try_nats/run_pub.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ async def main():

await nc.connect("nats://localhost:4222")

#
# todo x: 并发测试, 测试 run_multi_sub.py 基于 queue 方式订阅, 处理唯一性
#
for i in range(10):
await nc.publish("updates", f"Message {i}".encode())

await nc.publish("updates", b'Hello NATS!')

print("Message published!")
Expand Down

0 comments on commit 5a9fcab

Please sign in to comment.