0. Intro
빨리 NATs io 서버 띄우고 다른거 진행해야 하는데 자꾸 보다가 다른거 하다가 돌아오면 까먹는다. 그래서 진행이 안 되고 있다.
후딱 정리하고 다음으로 넘어가야겠다. 역시 일 하는 중 쓰는 블로그 효율이 제일 좋다.
이 글은 그냥 제가 후딱 보려고 대충 적었습니다. 참고가 안 될 것 으로 생각됩니다.
레퍼런스 좋아요. 그쪽 링크로 들어가서 보세요.
1. What is Nats? - Features
- Open source cloud native messaging system
- Performance, simplicity, security and availability
- Multple communication patterns
- completely distributed platform
- wild card subscribers
- fanout
- load balanced
- request/reply
- publish/subscribe
- selfish optimization - protect against slow consumer
- self healing server-client connections -dial tone
- publisher rate limiting
- streams
2. Delivery modes
- At most once (Core) (NATS server / NATS)
- At least once (NATS streaming & Jet stream)
3. NATS in Docker
- docker image from docker hub
- image name => nats
- docker run --name nats --rm -p 4222:4222 nats
- with using telnet localhost 4222, you can easily publish messages
- pub ${subject_name} ${length_of_message}
- pub com.test 5 => publish subject name "com.test" and the message length is 5
- hello => the message "hello" which the length is 5
- you should see "+OK"
- make sure the docker container is running
- nats client
- pip install nats.py **
import asyncio
import nats
from nats.errors import ConnectionClosedError, TimeoutError, NoServersError
async def main():
# It is very likely that the demo server will see traffic from clients other than yours.
# To avoid this, start your own locally and modify the example to use it.
nc = await nats.connect("nats://demo.nats.io:4222")
# You can also use the following for TLS against the demo server.
#
# nc = await nats.connect("tls://demo.nats.io:4443")
async def message_handler(msg):
subject = msg.subject
reply = msg.reply
data = msg.data.decode()
print("Received a message on '{subject} {reply}': {data}".format(
subject=subject, reply=reply, data=data))
# Simple publisher and async subscriber via coroutine.
sub = await nc.subscribe("foo", cb=message_handler)
# Stop receiving after 2 messages.
# 위에서 command line 에서 pub 했던것과 같습니다
await sub.unsubscribe(limit=2)
await nc.publish("foo", b'Hello')
await nc.publish("foo", b'World')
await nc.publish("foo", b'!!!!!')
# Synchronous style with iterator also supported.
sub = await nc.subscribe("bar")
await nc.publish("bar", b'First')
await nc.publish("bar", b'Second')
try:
async for msg in sub.messages:
print(f"Received a message on '{msg.subject} {msg.reply}': {msg.data.decode()}")
await sub.unsubscribe()
except Exception as e:
pass
async def help_request(msg):
print(f"Received a message on '{msg.subject} {msg.reply}': {msg.data.decode()}")
await nc.publish(msg.reply, b'I can help')
# Use queue named 'workers' for distributing requests
# among subscribers.
sub = await nc.subscribe("help", "workers", help_request)
# Send a request and expect a single response
# and trigger timeout if not faster than 500 ms.
try:
response = await nc.request("help", b'help me', timeout=0.5)
print("Received response: {message}".format(
message=response.data.decode()))
except TimeoutError:
print("Request timed out")
# Remove interest in subscription.
await sub.unsubscribe()
# Terminate connection to NATS.
await nc.drain()
if __name__ == '__main__':
asyncio.run(main())
4. Reference
'공부 중 메모' 카테고리의 다른 글
ARIMA 와 나머지들 (4) | 2024.08.01 |
---|---|
Nvidia DeepStream(1) - [to do] (8) | 2022.03.23 |
Docker_01_Container (5) | 2022.03.16 |
댓글