Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds unsubscribe method #2

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions goingnats.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

Check if __name__ == "__main__" for full example
"""
__version__ = "2021.4.0"
__version__ = "2021.9.0"

import json
import queue
Expand Down Expand Up @@ -76,6 +76,20 @@ def subscribe(self, *, subject):
self._sid += 1
try:
self._send([b"SUB", SPACE, subject, SPACE, _int_to_bytes(self._sid)])
return self._sid
except TypeError:
raise TypeError("subject must be bytes-like") from None

def unsubscribe(self, *, sid, max_msgs=None):
"""
unsubscribe from subscription id
https://docs.nats.io/nats-protocol/nats-protocol#unsub
"""
try:
cmd = [b"UNSUB", SPACE, _int_to_bytes(sid)]
if max_msgs is not None:
cmd.append([SPACE, _int_to_bytes(max_msgs)])
self._send(cmd)
except TypeError:
raise TypeError("subject must be bytes-like") from None

Expand Down Expand Up @@ -252,7 +266,7 @@ def responder():

# application
with Client(name="consumer") as client:
client.subscribe(subject=b"time.time")
sid = client.subscribe(subject=b"time.time")
received = 0
response = None
while received < 5:
Expand All @@ -264,3 +278,4 @@ def responder():
# request response are blocking
response = client.request(subject=b"today", payload=b"%Y%m%d")
print(response)
client.unsubscribe(sid)