├── .gitignore ├── LICENSE ├── README.md ├── connect_creds.py ├── connect_default.py ├── connect_multiple.py ├── connect_name.py ├── connect_nkey.py ├── connect_options.py ├── connect_pedantic.py ├── connect_status.py ├── connect_tls.py ├── connect_tls_url.py ├── connect_token.py ├── connect_token_url.py ├── connect_url.py ├── connect_userpass.py ├── connect_userpass_url.py ├── connect_verbose.py ├── dev.org ├── drain_conn.py ├── drain_sub.py ├── error_listener.py ├── flush.py ├── max_payload.py ├── no_echo.py ├── notapplicable.txt ├── ping_20s.py ├── ping_5.py ├── publish_bytes.py ├── publish_json.py ├── publish_with_reply.py ├── reconnect_10s.py ├── reconnect_10x.py ├── reconnect_event.py ├── reconnect_no_random.py ├── reconnect_none.py ├── request_reply.py ├── slow_listener.py ├── sub_pending_limits.py ├── subscribe_arrow.py ├── subscribe_async.py ├── subscribe_json.py ├── subscribe_queue.py ├── subscribe_star.py ├── subscribe_w_reply.py ├── unsubscribe.py ├── unsubscribe_auto.py └── wildcard_tester.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![](https://raw.githubusercontent.com/nats-io/nats-site/master/src/img/large-logo.png) 2 | 3 | # NATS - Python Examples 4 | 5 | [Python](https://www.python.org) examples for the [NATS messaging system](https://nats.io). 6 | 7 | [![License Apache 2](https://img.shields.io/badge/License-Apache2-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0) 8 | 9 | ## Introduction 10 | 11 | These are the Python Asyncio examples used on [nats.io](https://nats.io). 12 | -------------------------------------------------------------------------------- /connect_creds.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | # [begin connect_creds] 6 | nc = NATS() 7 | 8 | async def error_cb(e): 9 | print("Error:", e) 10 | 11 | await nc.connect("nats://localhost:4222", 12 | user_credentials="path_to_creds_file", 13 | error_cb=error_cb, 14 | ) 15 | 16 | # Do something with the connection 17 | 18 | await nc.close() 19 | 20 | # [end connect_creds] 21 | 22 | loop = asyncio.get_event_loop() 23 | loop.run_until_complete(example()) 24 | loop.close() 25 | -------------------------------------------------------------------------------- /connect_default.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | # [begin connect_default] 6 | nc = NATS() 7 | await nc.connect() 8 | 9 | # Do something with the connection 10 | 11 | await nc.close() 12 | 13 | # [end connect_default] 14 | 15 | loop = asyncio.get_event_loop() 16 | loop.run_until_complete(example()) 17 | loop.close() 18 | -------------------------------------------------------------------------------- /connect_multiple.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | # [begin connect_multiple] 6 | nc = NATS() 7 | await nc.connect(servers=[ 8 | "nats://127.0.0.1:1222", 9 | "nats://127.0.0.1:1223", 10 | "nats://127.0.0.1:1224" 11 | ]) 12 | 13 | # Do something with the connection 14 | 15 | await nc.close() 16 | 17 | # [end connect_multiple] 18 | 19 | loop = asyncio.get_event_loop() 20 | loop.run_until_complete(example()) 21 | loop.close() 22 | -------------------------------------------------------------------------------- /connect_name.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin connect_name] 7 | nc = NATS() 8 | 9 | await nc.connect(servers=["nats://demo.nats.io:4222"], name="my-connection") 10 | 11 | # Do something with the connection. 12 | 13 | # [end connect_name] 14 | 15 | await nc.close() 16 | 17 | loop = asyncio.get_event_loop() 18 | loop.run_until_complete(example()) 19 | loop.close() 20 | -------------------------------------------------------------------------------- /connect_nkey.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | # [begin connect_nkey] 6 | nc = NATS() 7 | 8 | async def error_cb(e): 9 | print("Error:", e) 10 | 11 | await nc.connect("nats://localhost:4222", 12 | nkeys_seed="./path/to/nkeys/user.nk", 13 | error_cb=error_cb, 14 | ) 15 | 16 | # Do something with the connection 17 | 18 | await nc.close() 19 | 20 | # [end connect_nkey] 21 | 22 | loop = asyncio.get_event_loop() 23 | loop.run_until_complete(example()) 24 | loop.close() 25 | -------------------------------------------------------------------------------- /connect_options.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | # [begin connect_options] 6 | nc = NATS() 7 | await nc.connect(connect_timeout=2) 8 | 9 | # Do something with the connection 10 | 11 | await nc.close() 12 | 13 | # [end connect_options] 14 | 15 | loop = asyncio.get_event_loop() 16 | loop.run_until_complete(example()) 17 | loop.close() 18 | -------------------------------------------------------------------------------- /connect_pedantic.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin connect_pedantic] 7 | nc = NATS() 8 | 9 | await nc.connect(servers=["nats://demo.nats.io:4222"], pedantic=True) 10 | 11 | # Do something with the connection. 12 | 13 | # [end connect_pedantic] 14 | 15 | await nc.close() 16 | 17 | loop = asyncio.get_event_loop() 18 | loop.run_until_complete(example()) 19 | loop.close() 20 | -------------------------------------------------------------------------------- /connect_status.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin connect_status] 7 | nc = NATS() 8 | 9 | await nc.connect( 10 | servers=["nats://demo.nats.io:4222"], 11 | ) 12 | 13 | # Do something with the connection. 14 | 15 | print("The connection is connected?", nc.is_connected) 16 | 17 | while True: 18 | if nc.is_reconnecting: 19 | print("Reconnecting to NATS...") 20 | break 21 | await asyncio.sleep(1) 22 | 23 | await nc.close() 24 | 25 | print("The connection is closed?", nc.is_closed) 26 | 27 | # [end connect_status] 28 | 29 | loop = asyncio.get_event_loop() 30 | loop.run_until_complete(example()) 31 | loop.close() 32 | -------------------------------------------------------------------------------- /connect_tls.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import ssl 3 | from nats.aio.client import Client as NATS 4 | 5 | async def example(): 6 | 7 | # [begin connect_tls] 8 | nc = NATS() 9 | 10 | ssl_ctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH) 11 | ssl_ctx.load_verify_locations('ca.pem') 12 | ssl_ctx.load_cert_chain(certfile='client-cert.pem', 13 | keyfile='client-key.pem') 14 | await nc.connect(io_loop=loop, tls=ssl_ctx) 15 | 16 | await nc.connect(servers=["nats://demo.nats.io:4222"], tls=ssl_ctx) 17 | 18 | # Do something with the connection. 19 | 20 | # [end connect_tls] 21 | 22 | await nc.close() 23 | 24 | loop = asyncio.get_event_loop() 25 | loop.run_until_complete(example()) 26 | loop.close() 27 | -------------------------------------------------------------------------------- /connect_tls_url.py: -------------------------------------------------------------------------------- 1 | # [begin connect_tls_url] 2 | import asyncio 3 | import ssl 4 | import certifi 5 | from nats.aio.client import Client as NATS 6 | from nats.aio.errors import ErrTimeout 7 | 8 | async def run(loop): 9 | nc = NATS() 10 | 11 | # If using Python 3.7 in OS X and getting SSL errors, run first: 12 | # 13 | # /Applications/Python\ 3.7/Install\ Certificates.command 14 | # 15 | # Setting the tls as the scheme will use same defaults as `ssl.create_default_context()` 16 | # 17 | await nc.connect("tls://demo.nats.io:4443", loop=loop) 18 | 19 | async def message_handler(msg): 20 | subject = msg.subject 21 | reply = msg.reply 22 | data = msg.data.decode() 23 | print("Received a message on '{subject} {reply}': {data}".format( 24 | subject=subject, reply=reply, data=data)) 25 | 26 | # Simple publisher and async subscriber via coroutine. 27 | sid = await nc.subscribe("foo", cb=message_handler) 28 | await nc.flush() 29 | 30 | # Stop receiving after 2 messages. 31 | await nc.auto_unsubscribe(sid, 2) 32 | await nc.publish("foo", b'Hello') 33 | await nc.publish("foo", b'World') 34 | await nc.publish("foo", b'!!!!!') 35 | await asyncio.sleep(1, loop=loop) 36 | await nc.close() 37 | # [end connect_tls_url] 38 | 39 | if __name__ == '__main__': 40 | loop = asyncio.get_event_loop() 41 | loop.run_until_complete(run(loop)) 42 | loop.close() 43 | -------------------------------------------------------------------------------- /connect_token.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin connect_token] 7 | nc = NATS() 8 | 9 | await nc.connect(servers=["nats://mytoken@demo.nats.io:4222"]) 10 | 11 | # Do something with the connection. 12 | 13 | # [end connect_token] 14 | 15 | await nc.close() 16 | 17 | loop = asyncio.get_event_loop() 18 | loop.run_until_complete(example()) 19 | loop.close() 20 | -------------------------------------------------------------------------------- /connect_token_url.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin connect_token_url] 7 | nc = NATS() 8 | 9 | await nc.connect(servers=["nats://mytoken@demo.nats.io:4222"]) 10 | 11 | # Do something with the connection. 12 | 13 | # [end connect_token_url] 14 | 15 | await nc.close() 16 | 17 | loop = asyncio.get_event_loop() 18 | loop.run_until_complete(example()) 19 | loop.close() 20 | -------------------------------------------------------------------------------- /connect_url.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | # [begin connect_url] 6 | nc = NATS() 7 | await nc.connect(servers=["nats://demo.nats.io:4222"]) 8 | 9 | # Do something with the connection 10 | 11 | await nc.close() 12 | 13 | # [end connect_url] 14 | 15 | loop = asyncio.get_event_loop() 16 | loop.run_until_complete(example()) 17 | loop.close() 18 | -------------------------------------------------------------------------------- /connect_userpass.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin connect_userpass] 7 | nc = NATS() 8 | 9 | await nc.connect(servers=["nats://myname:password@demo.nats.io:4222"]) 10 | 11 | # Do something with the connection. 12 | 13 | # [end connect_userpass] 14 | 15 | await nc.close() 16 | 17 | loop = asyncio.get_event_loop() 18 | loop.run_until_complete(example()) 19 | loop.close() 20 | -------------------------------------------------------------------------------- /connect_userpass_url.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin connect_userpass_url] 7 | nc = NATS() 8 | 9 | await nc.connect(servers=["nats://myname:password@demo.nats.io:4222"]) 10 | 11 | # Do something with the connection. 12 | 13 | # [end connect_userpass_url] 14 | 15 | await nc.close() 16 | 17 | loop = asyncio.get_event_loop() 18 | loop.run_until_complete(example()) 19 | loop.close() 20 | -------------------------------------------------------------------------------- /connect_verbose.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin connect_verbose] 7 | nc = NATS() 8 | 9 | await nc.connect(servers=["nats://demo.nats.io:4222"], verbose=True) 10 | 11 | # Do something with the connection. 12 | 13 | # [end connect_verbose] 14 | 15 | await nc.close() 16 | 17 | loop = asyncio.get_event_loop() 18 | loop.run_until_complete(example()) 19 | loop.close() 20 | -------------------------------------------------------------------------------- /dev.org: -------------------------------------------------------------------------------- 1 | #+TITLE: Python Examples 2 | #+startup: showeverything 3 | #+property: header-args :results output 4 | 5 | ** COMMENT Notes 6 | 7 | #+BEGIN_SRC emacs-lisp 8 | (setq org-babel-python-command "python3") 9 | #+END_SRC 10 | 11 | ** [35/35] [100%] Progress 12 | 13 | *** DONE connect_default 14 | 15 | #+BEGIN_SRC python :tangle connect_default.py 16 | import asyncio 17 | from nats.aio.client import Client as NATS 18 | 19 | async def example(): 20 | # [begin connect_default] 21 | nc = NATS() 22 | await nc.connect() 23 | 24 | # Do something with the connection 25 | 26 | await nc.close() 27 | 28 | # [end connect_default] 29 | 30 | loop = asyncio.get_event_loop() 31 | loop.run_until_complete(example()) 32 | loop.close() 33 | #+END_SRC 34 | 35 | #+RESULTS: 36 | 37 | *** DONE connect_url 38 | 39 | #+BEGIN_SRC python :tangle connect_url.py 40 | import asyncio 41 | from nats.aio.client import Client as NATS 42 | 43 | async def example(): 44 | # [begin connect_url] 45 | nc = NATS() 46 | await nc.connect(servers=["nats://demo.nats.io:4222"]) 47 | 48 | # Do something with the connection 49 | 50 | await nc.close() 51 | 52 | # [end connect_url] 53 | 54 | loop = asyncio.get_event_loop() 55 | loop.run_until_complete(example()) 56 | loop.close() 57 | #+END_SRC 58 | 59 | #+RESULTS: 60 | 61 | *** COMMENT connect_options 62 | 63 | #+BEGIN_SRC python :tangle connect_url.py 64 | import asyncio 65 | from nats.aio.client import Client as NATS 66 | 67 | async def example(): 68 | # [begin connect_url] 69 | nc = NATS() 70 | await nc.connect(servers=["nats://demo.nats.io:4222"]) 71 | 72 | # Do something with the connection 73 | 74 | await nc.close() 75 | 76 | # [end connect_url] 77 | 78 | loop = asyncio.get_event_loop() 79 | loop.run_until_complete(example()) 80 | loop.close() 81 | #+END_SRC 82 | 83 | *** DONE connect_multiple 84 | 85 | #+BEGIN_SRC python :tangle connect_multiple.py 86 | import asyncio 87 | from nats.aio.client import Client as NATS 88 | 89 | async def example(): 90 | # [begin connect_multiple] 91 | nc = NATS() 92 | await nc.connect(servers=[ 93 | "nats://127.0.0.1:1222", 94 | "nats://127.0.0.1:1223", 95 | "nats://127.0.0.1:1224" 96 | ]) 97 | 98 | # Do something with the connection 99 | 100 | await nc.close() 101 | 102 | # [end connect_multiple] 103 | 104 | loop = asyncio.get_event_loop() 105 | loop.run_until_complete(example()) 106 | loop.close() 107 | #+END_SRC 108 | 109 | #+RESULTS: 110 | 111 | *** DONE reconnect_no_random 112 | 113 | #+BEGIN_SRC python :tangle reconnect_no_random.py 114 | import asyncio 115 | from nats.aio.client import Client as NATS 116 | 117 | async def example(): 118 | # [begin reconnect_no_random] 119 | nc = NATS() 120 | await nc.connect( 121 | servers=[ 122 | "nats://127.0.0.1:1222", 123 | "nats://127.0.0.1:1223", 124 | "nats://127.0.0.1:1224" 125 | ], 126 | dont_randomize=True, 127 | ) 128 | 129 | # Do something with the connection 130 | 131 | await nc.close() 132 | 133 | # [end reconnect_no_random] 134 | 135 | loop = asyncio.get_event_loop() 136 | loop.run_until_complete(example()) 137 | loop.close() 138 | #+END_SRC 139 | 140 | #+RESULTS: 141 | 142 | *** DONE reconnect_none 143 | 144 | #+BEGIN_SRC python :tangle reconnect_none.py 145 | import asyncio 146 | from nats.aio.client import Client as NATS 147 | 148 | async def example(): 149 | # [begin reconnect_none] 150 | nc = NATS() 151 | await nc.connect( 152 | servers=[ 153 | "nats://127.0.0.1:1222", 154 | "nats://127.0.0.1:1223", 155 | "nats://127.0.0.1:1224" 156 | ], 157 | allow_reconnect=False, 158 | ) 159 | 160 | # Do something with the connection 161 | 162 | await nc.close() 163 | 164 | # [end reconnect_none] 165 | 166 | loop = asyncio.get_event_loop() 167 | loop.run_until_complete(example()) 168 | loop.close() 169 | #+END_SRC 170 | 171 | #+RESULTS: 172 | 173 | *** DONE reconnect_10x 174 | 175 | #+BEGIN_SRC python :tangle reconnect_10x.py 176 | import asyncio 177 | from nats.aio.client import Client as NATS 178 | 179 | async def example(): 180 | # [begin reconnect_10x] 181 | nc = NATS() 182 | await nc.connect( 183 | servers=["nats://demo.nats.io:4222"], 184 | max_reconnect_attempts=10, 185 | ) 186 | 187 | # Do something with the connection 188 | 189 | await nc.close() 190 | 191 | # [end reconnect_10x] 192 | 193 | loop = asyncio.get_event_loop() 194 | loop.run_until_complete(example()) 195 | loop.close() 196 | #+END_SRC 197 | 198 | #+RESULTS: 199 | 200 | *** COMMENT reconnect_5mb 201 | 202 | #+BEGIN_SRC python :tangle reconnect_5mb.py 203 | import asyncio 204 | from nats.aio.client import Client as NATS 205 | 206 | async def example(): 207 | # [begin reconnect_5mb] 208 | nc = NATS() 209 | await nc.connect( 210 | servers=["nats://demo.nats.io:4222"], 211 | max_reconnect_attempts=10, 212 | ) 213 | 214 | # Do something with the connection 215 | 216 | await nc.close() 217 | 218 | # [end reconnect_5mb] 219 | 220 | loop = asyncio.get_event_loop() 221 | loop.run_until_complete(example()) 222 | loop.close() 223 | #+END_SRC 224 | 225 | *** DONE reconnect_10s 226 | 227 | #+BEGIN_SRC python :tangle reconnect_10s.py 228 | import asyncio 229 | from nats.aio.client import Client as NATS 230 | 231 | async def example(): 232 | # [begin reconnect_10s] 233 | nc = NATS() 234 | await nc.connect( 235 | servers=["nats://demo.nats.io:4222"], 236 | reconnect_time_wait=10, 237 | ) 238 | 239 | # Do something with the connection 240 | 241 | await nc.close() 242 | 243 | # [end reconnect_10s] 244 | 245 | loop = asyncio.get_event_loop() 246 | loop.run_until_complete(example()) 247 | loop.close() 248 | #+END_SRC 249 | 250 | #+RESULTS: 251 | 252 | *** DONE reconnect_event 253 | 254 | #+BEGIN_SRC python :tangle reconnect_event.py 255 | import asyncio 256 | from nats.aio.client import Client as NATS 257 | 258 | async def example(): 259 | 260 | # [begin reconnect_event] 261 | nc = NATS() 262 | 263 | async def disconnected_cb(): 264 | print("Got disconnected!") 265 | 266 | async def reconnected_cb(): 267 | # See who we are connected to on reconnect. 268 | print("Got reconnected to {url}".format(url=nc.connected_url.netloc)) 269 | 270 | await nc.connect( 271 | servers=["nats://127.0.0.1:4222"], 272 | reconnect_time_wait=10, 273 | reconnected_cb=reconnected_cb, 274 | disconnected_cb=disconnected_cb, 275 | ) 276 | 277 | # Do something with the connection. 278 | 279 | # [end reconnect_event] 280 | 281 | while True: 282 | if nc.is_closed: 283 | break 284 | await asyncio.sleep(1) 285 | 286 | await nc.close() 287 | 288 | loop = asyncio.get_event_loop() 289 | loop.run_until_complete(example()) 290 | loop.close() 291 | #+END_SRC 292 | 293 | *** DONE ping_20s 294 | 295 | #+BEGIN_SRC python :tangle ping_20s.py 296 | import asyncio 297 | from nats.aio.client import Client as NATS 298 | 299 | async def example(): 300 | 301 | # [begin ping_20s] 302 | nc = NATS() 303 | 304 | await nc.connect( 305 | servers=["nats://demo.nats.io:4222"], 306 | # Set Ping Interval to 20 seconds 307 | ping_interval=20, 308 | ) 309 | 310 | # Do something with the connection. 311 | 312 | # [end ping_20s] 313 | 314 | while True: 315 | if nc.is_closed: 316 | break 317 | await asyncio.sleep(1) 318 | 319 | await nc.close() 320 | 321 | loop = asyncio.get_event_loop() 322 | loop.run_until_complete(example()) 323 | loop.close() 324 | #+END_SRC 325 | 326 | *** DONE ping_5 327 | 328 | #+BEGIN_SRC python :tangle ping_5.py 329 | import asyncio 330 | from nats.aio.client import Client as NATS 331 | 332 | async def example(): 333 | 334 | # [begin ping_5] 335 | nc = NATS() 336 | 337 | await nc.connect( 338 | servers=["nats://127.0.0.1:4222"], 339 | # Set maximum number of PINGs out without getting a PONG back 340 | # before the connection will be disconnected as a stale connection. 341 | max_outstanding_pings=5, 342 | ping_interval=1, 343 | ) 344 | 345 | # Do something with the connection. 346 | 347 | # [end ping_5] 348 | 349 | while True: 350 | if nc.is_closed: 351 | break 352 | await asyncio.sleep(1) 353 | 354 | await nc.close() 355 | 356 | loop = asyncio.get_event_loop() 357 | loop.run_until_complete(example()) 358 | loop.close() 359 | #+END_SRC 360 | 361 | *** DONE max_payload 362 | 363 | #+BEGIN_SRC python :tangle max_payload.py 364 | import asyncio 365 | from nats.aio.client import Client as NATS 366 | 367 | async def example(): 368 | 369 | # [begin max_payload] 370 | nc = NATS() 371 | 372 | await nc.connect(servers=["nats://demo.nats.io:4222"]) 373 | 374 | print("Maximum payload is %d bytes" % nc.max_payload) 375 | 376 | # Do something with the max payload. 377 | 378 | # [end max_payload] 379 | 380 | await nc.close() 381 | 382 | loop = asyncio.get_event_loop() 383 | loop.run_until_complete(example()) 384 | loop.close() 385 | #+END_SRC 386 | 387 | #+RESULTS: 388 | : Maximum payload is 1048576 bytes 389 | 390 | *** COMMENT control_2k 391 | *** COMMENT no_echo 392 | *** DONE connect_pedantic 393 | 394 | #+BEGIN_SRC python :tangle connect_pedantic.py 395 | import asyncio 396 | from nats.aio.client import Client as NATS 397 | 398 | async def example(): 399 | 400 | # [begin connect_pedantic] 401 | nc = NATS() 402 | 403 | await nc.connect(servers=["nats://127.0.0.1:4222"], pedantic=True) 404 | 405 | # Do something with the connection. 406 | 407 | # [end connect_pedantic] 408 | 409 | await nc.close() 410 | 411 | loop = asyncio.get_event_loop() 412 | loop.run_until_complete(example()) 413 | loop.close() 414 | #+END_SRC 415 | 416 | #+RESULTS: 417 | 418 | *** DONE connect_verbose 419 | 420 | #+BEGIN_SRC python :tangle connect_verbose.py 421 | import asyncio 422 | from nats.aio.client import Client as NATS 423 | 424 | async def example(): 425 | 426 | # [begin connect_verbose] 427 | nc = NATS() 428 | 429 | await nc.connect(servers=["nats://127.0.0.1:4222"], verbose=True) 430 | 431 | # Do something with the connection. 432 | 433 | # [end connect_verbose] 434 | 435 | await nc.close() 436 | 437 | loop = asyncio.get_event_loop() 438 | loop.run_until_complete(example()) 439 | loop.close() 440 | #+END_SRC 441 | 442 | #+RESULTS: 443 | 444 | *** DONE connect_name 445 | 446 | #+BEGIN_SRC python :tangle connect_name.py 447 | import asyncio 448 | from nats.aio.client import Client as NATS 449 | 450 | async def example(): 451 | 452 | # [begin connect_name] 453 | nc = NATS() 454 | 455 | await nc.connect(servers=["nats://127.0.0.1:4222"], name="my-connection") 456 | 457 | # Do something with the connection. 458 | 459 | # [end connect_name] 460 | 461 | await nc.close() 462 | 463 | loop = asyncio.get_event_loop() 464 | loop.run_until_complete(example()) 465 | loop.close() 466 | #+END_SRC 467 | 468 | #+RESULTS: 469 | 470 | *** DONE connect_tls 471 | 472 | #+BEGIN_SRC python :tangle connect_tls.py 473 | import asyncio 474 | import ssl 475 | from nats.aio.client import Client as NATS 476 | 477 | async def example(): 478 | 479 | # [begin connect_tls] 480 | nc = NATS() 481 | 482 | ssl_ctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH) 483 | ssl_ctx.load_verify_locations('ca.pem') 484 | ssl_ctx.load_cert_chain(certfile='client-cert.pem', 485 | keyfile='client-key.pem') 486 | await nc.connect(io_loop=loop, tls=ssl_ctx) 487 | 488 | await nc.connect(servers=["nats://127.0.0.1:4222"], tls=ssl_ctx) 489 | 490 | # Do something with the connection. 491 | 492 | # [end connect_tls] 493 | 494 | await nc.close() 495 | 496 | loop = asyncio.get_event_loop() 497 | loop.run_until_complete(example()) 498 | loop.close() 499 | #+END_SRC 500 | 501 | *** COMMENT connect_tls_url 502 | *** DONE connect_userpass 503 | 504 | #+BEGIN_SRC python :tangle connect_userpass.py 505 | import asyncio 506 | from nats.aio.client import Client as NATS 507 | 508 | async def example(): 509 | 510 | # [begin connect_userpass] 511 | nc = NATS() 512 | 513 | await nc.connect(servers=["nats://myname:password@127.0.0.1:4222"]) 514 | 515 | # Do something with the connection. 516 | 517 | # [end connect_userpass] 518 | 519 | await nc.close() 520 | 521 | loop = asyncio.get_event_loop() 522 | loop.run_until_complete(example()) 523 | loop.close() 524 | #+END_SRC 525 | 526 | *** DONE connect_userpass_url 527 | 528 | #+BEGIN_SRC python :tangle connect_userpass_url.py 529 | import asyncio 530 | from nats.aio.client import Client as NATS 531 | 532 | async def example(): 533 | 534 | # [begin connect_userpass_url] 535 | nc = NATS() 536 | 537 | await nc.connect(servers=["nats://myname:password@127.0.0.1:4222"]) 538 | 539 | # Do something with the connection. 540 | 541 | # [end connect_userpass_url] 542 | 543 | await nc.close() 544 | 545 | loop = asyncio.get_event_loop() 546 | loop.run_until_complete(example()) 547 | loop.close() 548 | #+END_SRC 549 | 550 | #+RESULTS: 551 | 552 | *** DONE connect_token 553 | 554 | #+BEGIN_SRC python :tangle connect_token.py 555 | import asyncio 556 | from nats.aio.client import Client as NATS 557 | 558 | async def example(): 559 | 560 | # [begin connect_token] 561 | nc = NATS() 562 | 563 | await nc.connect(servers=["nats://mytoken@127.0.0.1:4222"]) 564 | 565 | # Do something with the connection. 566 | 567 | # [end connect_token] 568 | 569 | await nc.close() 570 | 571 | loop = asyncio.get_event_loop() 572 | loop.run_until_complete(example()) 573 | loop.close() 574 | #+END_SRC 575 | 576 | #+RESULTS: 577 | 578 | *** DONE connect_token_url 579 | 580 | #+BEGIN_SRC python :tangle connect_token_url.py 581 | import asyncio 582 | from nats.aio.client import Client as NATS 583 | 584 | async def example(): 585 | 586 | # [begin connect_token_url] 587 | nc = NATS() 588 | 589 | await nc.connect(servers=["nats://mytoken@127.0.0.1:4222"]) 590 | 591 | # Do something with the connection. 592 | 593 | # [end connect_token_url] 594 | 595 | await nc.close() 596 | 597 | loop = asyncio.get_event_loop() 598 | loop.run_until_complete(example()) 599 | loop.close() 600 | #+END_SRC 601 | 602 | *** DONE publish_bytes 603 | 604 | #+BEGIN_SRC python :tangle publish_bytes.py 605 | import asyncio 606 | from nats.aio.client import Client as NATS 607 | 608 | async def example(): 609 | 610 | # [begin publish_bytes] 611 | nc = NATS() 612 | 613 | await nc.connect(servers=["nats://127.0.0.1:4222"]) 614 | 615 | await nc.publish("updates", b'All is Well') 616 | 617 | # [end publish_bytes] 618 | 619 | await nc.close() 620 | 621 | loop = asyncio.get_event_loop() 622 | loop.run_until_complete(example()) 623 | loop.close() 624 | #+END_SRC 625 | 626 | #+RESULTS: 627 | 628 | *** DONE publish_json 629 | 630 | #+BEGIN_SRC python :tangle publish_json.py 631 | import asyncio 632 | import json 633 | from nats.aio.client import Client as NATS 634 | 635 | async def example(): 636 | 637 | # [begin publish_json] 638 | nc = NATS() 639 | 640 | await nc.connect(servers=["nats://127.0.0.1:4222"]) 641 | 642 | await nc.publish("updates", json.dumps({"symbol": "GOOG", "price": 1200 }).encode()) 643 | 644 | # [end publish_json] 645 | 646 | await nc.close() 647 | 648 | loop = asyncio.get_event_loop() 649 | loop.run_until_complete(example()) 650 | loop.close() 651 | #+END_SRC 652 | 653 | #+RESULTS: 654 | 655 | *** DONE publish_with_reply 656 | 657 | #+BEGIN_SRC python :tangle publish_with_reply.py 658 | import asyncio 659 | import json 660 | from nats.aio.client import Client as NATS 661 | from nats.aio.utils import new_inbox 662 | 663 | async def example(): 664 | 665 | # [begin publish_with_reply] 666 | nc = NATS() 667 | 668 | future = asyncio.Future() 669 | 670 | async def sub(msg): 671 | nonlocal future 672 | future.set_result(msg) 673 | 674 | await nc.connect(servers=["nats://127.0.0.1:4222"]) 675 | await nc.subscribe("time", cb=sub) 676 | 677 | unique_reply_to = new_inbox() 678 | await nc.publish_request("time", unique_reply_to, b'') 679 | 680 | # Use the response 681 | msg = await asyncio.wait_for(future, 1) 682 | print("Reply:", msg) 683 | 684 | # [end publish_with_reply] 685 | 686 | await nc.close() 687 | 688 | loop = asyncio.get_event_loop() 689 | loop.run_until_complete(example()) 690 | loop.close() 691 | #+END_SRC 692 | 693 | #+RESULTS: 694 | : Reply: 695 | 696 | *** DONE request_reply 697 | 698 | #+BEGIN_SRC python :tangle request_reply.py 699 | import asyncio 700 | import json 701 | from nats.aio.client import Client as NATS 702 | from nats.aio.utils import new_inbox 703 | 704 | async def example(): 705 | 706 | # [begin request_reply] 707 | nc = NATS() 708 | 709 | async def sub(msg): 710 | await nc.publish(msg.reply, b'response') 711 | 712 | await nc.connect(servers=["nats://127.0.0.1:4222"]) 713 | await nc.subscribe("time", cb=sub) 714 | 715 | # Send the request 716 | try: 717 | msg = await nc.request("time", b'', timeout=1) 718 | # Use the response 719 | print("Reply:", msg) 720 | except asyncio.TimeoutError: 721 | print("Timed out waiting for response") 722 | 723 | # [end request_reply] 724 | 725 | await nc.close() 726 | 727 | loop = asyncio.get_event_loop() 728 | loop.run_until_complete(example()) 729 | loop.close() 730 | #+END_SRC 731 | 732 | #+RESULTS: 733 | : Reply: 734 | 735 | *** DONE flush 736 | 737 | #+BEGIN_SRC python :tangle flush.py 738 | import asyncio 739 | from nats.aio.client import Client as NATS 740 | 741 | async def example(): 742 | 743 | # [begin flush] 744 | nc = NATS() 745 | 746 | await nc.connect(servers=["nats://127.0.0.1:4222"]) 747 | 748 | await nc.publish("updates", b'All is Well') 749 | 750 | # Sends a PING and wait for a PONG from the server, up to the given timeout. 751 | # This gives guarantee that the server has processed above message. 752 | await nc.flush(timeout=1) 753 | 754 | # [end flush] 755 | 756 | await nc.close() 757 | 758 | loop = asyncio.get_event_loop() 759 | loop.run_until_complete(example()) 760 | loop.close() 761 | #+END_SRC 762 | 763 | *** COMMENT subscribe_sync 764 | *** DONE subscribe_async 765 | 766 | #+BEGIN_SRC python :tangle subscribe_async.py 767 | import asyncio 768 | from nats.aio.client import Client as NATS 769 | 770 | async def example(): 771 | 772 | # [begin subscribe_async] 773 | nc = NATS() 774 | 775 | await nc.connect(servers=["nats://127.0.0.1:4222"]) 776 | 777 | future = asyncio.Future() 778 | 779 | async def cb(msg): 780 | nonlocal future 781 | future.set_result(msg) 782 | 783 | await nc.subscribe("updates", cb=cb) 784 | await nc.publish("updates", b'All is Well') 785 | await nc.flush() 786 | 787 | # Wait for message to come in 788 | msg = await asyncio.wait_for(future, 1) 789 | 790 | # [end subscribe_async] 791 | print(msg) 792 | 793 | await nc.close() 794 | 795 | loop = asyncio.get_event_loop() 796 | loop.run_until_complete(example()) 797 | loop.close() 798 | #+END_SRC 799 | 800 | #+RESULTS: 801 | 802 | *** DONE subscribe_w_reply 803 | 804 | #+BEGIN_SRC python :tangle subscribe_w_reply.py 805 | import asyncio 806 | from nats.aio.client import Client as NATS 807 | from nats.aio.utils import new_inbox 808 | from datetime import datetime 809 | 810 | async def example(): 811 | 812 | # [begin subscribe_w_reply] 813 | nc = NATS() 814 | 815 | await nc.connect(servers=["nats://127.0.0.1:4222"]) 816 | 817 | future = asyncio.Future() 818 | 819 | async def cb(msg): 820 | nonlocal future 821 | future.set_result(msg) 822 | 823 | await nc.subscribe("time", cb=cb) 824 | 825 | await nc.publish_request("time", new_inbox(), b'What is the time?') 826 | await nc.flush() 827 | 828 | # Read the message 829 | msg = await asyncio.wait_for(future, 1) 830 | 831 | # Send the time 832 | time_as_bytes = "{}".format(datetime.now()).encode() 833 | await nc.publish(msg.reply, time_as_bytes) 834 | 835 | # [end subscribe_w_reply] 836 | 837 | await nc.close() 838 | 839 | loop = asyncio.get_event_loop() 840 | loop.run_until_complete(example()) 841 | loop.close() 842 | #+END_SRC 843 | 844 | #+RESULTS: 845 | : 2018-08-12 23:41:28.615782 846 | 847 | *** DONE unsubscribe 848 | 849 | #+BEGIN_SRC python :tangle unsubscribe.py 850 | import asyncio 851 | from nats.aio.client import Client as NATS 852 | 853 | async def example(): 854 | 855 | # [begin unsubscribe] 856 | nc = NATS() 857 | 858 | await nc.connect(servers=["nats://127.0.0.1:4222"]) 859 | 860 | future = asyncio.Future() 861 | 862 | async def cb(msg): 863 | nonlocal future 864 | future.set_result(msg) 865 | 866 | sid = await nc.subscribe("updates", cb=cb) 867 | await nc.publish("updates", b'All is Well') 868 | 869 | # Remove interest in subject 870 | await nc.unsubscribe(sid) 871 | 872 | # Won't be received... 873 | await nc.publish("updates", b'...') 874 | 875 | # [end unsubscribe] 876 | 877 | await nc.close() 878 | 879 | loop = asyncio.get_event_loop() 880 | loop.run_until_complete(example()) 881 | loop.close() 882 | #+END_SRC 883 | 884 | *** DONE unsubscribe_auto 885 | 886 | #+BEGIN_SRC python :tangle unsubscribe_auto.py 887 | import asyncio 888 | from nats.aio.client import Client as NATS 889 | 890 | async def example(): 891 | 892 | # [begin unsubscribe_auto] 893 | nc = NATS() 894 | 895 | await nc.connect(servers=["nats://127.0.0.1:4222"]) 896 | 897 | async def cb(msg): 898 | print(msg) 899 | 900 | sid = await nc.subscribe("updates", cb=cb) 901 | await nc.auto_unsubscribe(sid, 1) 902 | await nc.publish("updates", b'All is Well') 903 | 904 | # Won't be received... 905 | await nc.publish("updates", b'...') 906 | 907 | # [end unsubscribe_auto] 908 | 909 | await asyncio.sleep(1) 910 | 911 | await nc.close() 912 | 913 | loop = asyncio.get_event_loop() 914 | loop.run_until_complete(example()) 915 | loop.close() 916 | #+END_SRC 917 | 918 | *** COMMENT subscribe_json 919 | 920 | #+BEGIN_SRC python :tangle subscribe_json.py 921 | import asyncio 922 | import json 923 | from nats.aio.client import Client as NATS 924 | from nats.aio.utils import new_inbox 925 | 926 | async def example(): 927 | 928 | # [begin subscribe_json] 929 | nc = NATS() 930 | 931 | async def sub(msg): 932 | print(msg) 933 | # await nc.publish(msg.reply, b'response') 934 | 935 | await nc.connect(servers=["nats://127.0.0.1:4222"]) 936 | await nc.subscribe("updates", cb=sub) 937 | 938 | # Send the request 939 | try: 940 | msg = await nc.request("time", b'', timeout=1) 941 | # Use the response 942 | print("Reply:", msg) 943 | except asyncio.TimeoutError: 944 | print("Timed out waiting for response") 945 | 946 | # [end subscribe_json] 947 | 948 | await nc.close() 949 | 950 | loop = asyncio.get_event_loop() 951 | loop.run_until_complete(example()) 952 | loop.close() 953 | #+END_SRC 954 | 955 | *** DONE subscribe_star 956 | 957 | #+BEGIN_SRC python :tangle subscribe_star.py 958 | import asyncio 959 | from nats.aio.client import Client as NATS 960 | 961 | async def example(): 962 | 963 | # [begin subscribe_star] 964 | nc = NATS() 965 | 966 | await nc.connect(servers=["nats://127.0.0.1:4222"]) 967 | 968 | # Use queue to wait for 2 messages to arrive 969 | queue = asyncio.Queue() 970 | async def cb(msg): 971 | await queue.put_nowait(msg) 972 | 973 | await nc.subscribe("time.*.east", cb=cb) 974 | 975 | # Send 2 messages and wait for them to come in 976 | await nc.publish("time.A.east", b'A') 977 | await nc.publish("time.B.east", b'B') 978 | 979 | msg_A = await queue.get() 980 | msg_B = await queue.get() 981 | 982 | print("Msg A:", msg_A) 983 | print("Msg B:", msg_B) 984 | 985 | # [end subscribe_star] 986 | 987 | await nc.close() 988 | 989 | loop = asyncio.get_event_loop() 990 | loop.run_until_complete(example()) 991 | loop.close() 992 | #+END_SRC 993 | 994 | *** DONE subscribe_arrow 995 | 996 | #+BEGIN_SRC python :tangle subscribe_arrow.py 997 | import asyncio 998 | from nats.aio.client import Client as NATS 999 | 1000 | async def example(): 1001 | 1002 | # [begin subscribe_arrow] 1003 | nc = NATS() 1004 | 1005 | await nc.connect(servers=["nats://127.0.0.1:4222"]) 1006 | 1007 | # Use queue to wait for 4 messages to arrive 1008 | queue = asyncio.Queue() 1009 | async def cb(msg): 1010 | await queue.put(msg) 1011 | 1012 | await nc.subscribe("time.>", cb=cb) 1013 | 1014 | # Send 2 messages and wait for them to come in 1015 | await nc.publish("time.A.east", b'A') 1016 | await nc.publish("time.B.east", b'B') 1017 | await nc.publish("time.C.west", b'C') 1018 | await nc.publish("time.D.west", b'D') 1019 | 1020 | for i in range(0, 4): 1021 | msg = await queue.get() 1022 | print("Msg:", msg) 1023 | 1024 | await nc.close() 1025 | 1026 | # [end subscribe_arrow] 1027 | 1028 | loop = asyncio.get_event_loop() 1029 | loop.run_until_complete(example()) 1030 | loop.close() 1031 | #+END_SRC 1032 | 1033 | *** DONE subscribe_queue 1034 | 1035 | #+BEGIN_SRC python :tangle subscribe_queue.py 1036 | import asyncio 1037 | from nats.aio.client import Client as NATS 1038 | 1039 | async def example(): 1040 | 1041 | # [begin subscribe_queue] 1042 | nc = NATS() 1043 | 1044 | await nc.connect(servers=["nats://127.0.0.1:4222"]) 1045 | 1046 | future = asyncio.Future() 1047 | 1048 | async def cb(msg): 1049 | nonlocal future 1050 | future.set_result(msg) 1051 | 1052 | await nc.subscribe("updates", queue="workers", cb=cb) 1053 | await nc.publish("updates", b'All is Well') 1054 | 1055 | msg = await asyncio.wait_for(future, 1) 1056 | print("Msg", msg) 1057 | 1058 | # [end subscribe_queue] 1059 | 1060 | await nc.close() 1061 | 1062 | loop = asyncio.get_event_loop() 1063 | loop.run_until_complete(example()) 1064 | loop.close() 1065 | #+END_SRC 1066 | 1067 | *** DONE wildcard_tester 1068 | 1069 | #+BEGIN_SRC python :tangle wildcard_tester.py 1070 | import asyncio 1071 | from nats.aio.client import Client as NATS 1072 | 1073 | async def example(): 1074 | 1075 | # [begin wildcard_tester] 1076 | nc = NATS() 1077 | 1078 | await nc.connect(servers=["nats://127.0.0.1:4222"]) 1079 | 1080 | await nc.publish("time.us.east", b'...') 1081 | await nc.publish("time.us.east.atlanta", b'...') 1082 | 1083 | await nc.publish("time.eu.east", b'...') 1084 | await nc.publish("time.eu.east.warsaw", b'...') 1085 | 1086 | await nc.close() 1087 | 1088 | # [end wildcard_tester] 1089 | 1090 | loop = asyncio.get_event_loop() 1091 | loop.run_until_complete(example()) 1092 | loop.close() 1093 | #+END_SRC 1094 | 1095 | *** COMMENT connection_listener 1096 | 1097 | *** COMMENT servers_added 1098 | 1099 | *** DONE error_listener 1100 | 1101 | #+BEGIN_SRC python :tangle error_listener.py 1102 | import asyncio 1103 | from nats.aio.client import Client as NATS 1104 | 1105 | async def example(): 1106 | 1107 | # [begin error_listener] 1108 | nc = NATS() 1109 | 1110 | async def error_cb(e): 1111 | print("Error: ", e) 1112 | 1113 | await nc.connect( 1114 | servers=["nats://127.0.0.1:4222"], 1115 | reconnect_time_wait=10, 1116 | error_cb=error_cb, 1117 | ) 1118 | 1119 | # Do something with the connection. 1120 | 1121 | # [end error_listener] 1122 | 1123 | while True: 1124 | if nc.is_closed: 1125 | break 1126 | await asyncio.sleep(1) 1127 | 1128 | await nc.close() 1129 | 1130 | loop = asyncio.get_event_loop() 1131 | loop.run_until_complete(example()) 1132 | loop.close() 1133 | #+END_SRC 1134 | 1135 | *** DONE connect_status 1136 | 1137 | #+BEGIN_SRC python :tangle connect_status.py 1138 | import asyncio 1139 | from nats.aio.client import Client as NATS 1140 | 1141 | async def example(): 1142 | 1143 | # [begin connect_status] 1144 | nc = NATS() 1145 | 1146 | await nc.connect( 1147 | servers=["nats://127.0.0.1:4222"], 1148 | ) 1149 | 1150 | # Do something with the connection. 1151 | 1152 | print("The connection is connected?", nc.is_connected) 1153 | 1154 | while True: 1155 | if nc.is_reconnecting: 1156 | print("Reconnecting to NATS...") 1157 | break 1158 | await asyncio.sleep(1) 1159 | 1160 | await nc.close() 1161 | 1162 | print("The connection is closed?", nc.is_closed) 1163 | 1164 | # [end connect_status] 1165 | 1166 | loop = asyncio.get_event_loop() 1167 | loop.run_until_complete(example()) 1168 | loop.close() 1169 | #+END_SRC 1170 | 1171 | *** COMMENT slow_pending_limits 1172 | 1173 | #+BEGIN_SRC python :tangle slow_pending_limits.py 1174 | import asyncio 1175 | from nats.aio.client import Client as NATS 1176 | 1177 | async def example(): 1178 | 1179 | # [begin slow_pending_limits] 1180 | nc = NATS() 1181 | 1182 | await nc.connect( 1183 | servers=["nats://127.0.0.1:4222"], 1184 | ) 1185 | 1186 | # Do something with the connection. 1187 | 1188 | print("The connection is connected?", nc.is_connected) 1189 | 1190 | while True: 1191 | if nc.is_reconnecting: 1192 | print("Reconnecting to NATS...") 1193 | break 1194 | await asyncio.sleep(1) 1195 | 1196 | await nc.close() 1197 | 1198 | print("The connection is closed?", nc.is_closed) 1199 | 1200 | # [end slow_pending_limits] 1201 | 1202 | loop = asyncio.get_event_loop() 1203 | loop.run_until_complete(example()) 1204 | loop.close() 1205 | #+END_SRC 1206 | 1207 | *** DONE slow_listener 1208 | 1209 | #+BEGIN_SRC python :tangle slow_listener.py 1210 | import asyncio 1211 | import nats.aio.errors 1212 | from nats.aio.client import Client as NATS 1213 | 1214 | async def example(): 1215 | 1216 | # [begin slow_listener] 1217 | 1218 | nc = NATS() 1219 | 1220 | async def error_cb(e): 1221 | if type(e) is nats.aio.errors.ErrSlowConsumer: 1222 | print("Slow consumer error, unsubscribing from handling further messages...") 1223 | await nc.unsubscribe(e.sid) 1224 | 1225 | await nc.connect( 1226 | servers=["nats://127.0.0.1:4222"], 1227 | error_cb=error_cb, 1228 | ) 1229 | 1230 | msgs = [] 1231 | future = asyncio.Future() 1232 | async def cb(msg): 1233 | nonlocal msgs 1234 | nonlocal future 1235 | print(msg) 1236 | msgs.append(msg) 1237 | 1238 | if len(msgs) == 3: 1239 | # Head of line blocking on other messages caused 1240 | # by single message proccesing taking long... 1241 | await asyncio.sleep(1) 1242 | 1243 | await nc.subscribe("updates", cb=cb, pending_msgs_limit=5) 1244 | 1245 | for i in range(0, 10): 1246 | await nc.publish("updates", "msg #{}".format(i).encode()) 1247 | await asyncio.sleep(0) 1248 | 1249 | try: 1250 | await asyncio.wait_for(future, 1) 1251 | except asyncio.TimeoutError: 1252 | pass 1253 | 1254 | for msg in msgs: 1255 | print("[Received]", msg) 1256 | 1257 | await nc.close() 1258 | 1259 | # [end slow_listener] 1260 | 1261 | loop = asyncio.get_event_loop() 1262 | loop.run_until_complete(example()) 1263 | loop.close() 1264 | #+END_SRC 1265 | -------------------------------------------------------------------------------- /drain_conn.py: -------------------------------------------------------------------------------- 1 | # [begin drain_conn] 2 | import asyncio 3 | from nats.aio.client import Client as NATS 4 | 5 | async def example(loop): 6 | nc = NATS() 7 | 8 | await nc.connect("nats://127.0.0.1:4222", loop=loop) 9 | 10 | async def handler(msg): 11 | print("[Received] ", msg) 12 | await nc.publish(msg.reply, b'I can help') 13 | 14 | # Can check whether client is in draining state 15 | if nc.is_draining: 16 | print("Connection is draining") 17 | 18 | await nc.subscribe("help", "workers", cb=handler) 19 | await nc.flush() 20 | 21 | requests = [] 22 | for i in range(0, 10): 23 | request = nc.request("help", b'help!', timeout=1) 24 | requests.append(request) 25 | 26 | # Wait for all the responses 27 | responses = [] 28 | responses = await asyncio.gather(*requests) 29 | 30 | # Gracefully close the connection. 31 | await nc.drain() 32 | 33 | print("Received {} responses".format(len(responses))) 34 | # [end drain_conn] 35 | 36 | if __name__ == '__main__': 37 | loop = asyncio.get_event_loop() 38 | loop.run_until_complete(example(loop)) 39 | loop.close() 40 | -------------------------------------------------------------------------------- /drain_sub.py: -------------------------------------------------------------------------------- 1 | # [begin drain_sub] 2 | import asyncio 3 | from nats.aio.client import Client as NATS 4 | 5 | async def example(loop): 6 | nc = NATS() 7 | 8 | await nc.connect("nats://127.0.0.1:4222", loop=loop) 9 | 10 | async def handler(msg): 11 | print("[Received] ", msg) 12 | await nc.publish(msg.reply, b'I can help') 13 | 14 | # Can check whether client is in draining state 15 | if nc.is_draining: 16 | print("Connection is draining") 17 | 18 | sid = await nc.subscribe("help", "workers", cb=handler) 19 | await nc.flush() 20 | 21 | # Gracefully unsubscribe the subscription 22 | await nc.drain(sid) 23 | 24 | # [end drain_sub] 25 | 26 | requests = [] 27 | for i in range(0, 100): 28 | request = nc.request("help", b'help!', timeout=1) 29 | requests.append(request) 30 | 31 | 32 | # Wait for all the responses 33 | try: 34 | responses = [] 35 | responses = await asyncio.gather(*requests) 36 | except: 37 | pass 38 | 39 | print("Received {} responses".format(len(responses))) 40 | await nc.close() 41 | 42 | 43 | 44 | if __name__ == '__main__': 45 | loop = asyncio.get_event_loop() 46 | loop.run_until_complete(example(loop)) 47 | loop.close() 48 | -------------------------------------------------------------------------------- /error_listener.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin error_listener] 7 | nc = NATS() 8 | 9 | async def error_cb(e): 10 | print("Error: ", e) 11 | 12 | await nc.connect( 13 | servers=["nats://demo.nats.io:4222"], 14 | reconnect_time_wait=10, 15 | error_cb=error_cb, 16 | ) 17 | 18 | # Do something with the connection. 19 | 20 | # [end error_listener] 21 | 22 | while True: 23 | if nc.is_closed: 24 | break 25 | await asyncio.sleep(1) 26 | 27 | await nc.close() 28 | 29 | loop = asyncio.get_event_loop() 30 | loop.run_until_complete(example()) 31 | loop.close() 32 | -------------------------------------------------------------------------------- /flush.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin flush] 7 | nc = NATS() 8 | 9 | await nc.connect(servers=["nats://demo.nats.io:4222"]) 10 | 11 | await nc.publish("updates", b'All is Well') 12 | 13 | # Sends a PING and wait for a PONG from the server, up to the given timeout. 14 | # This gives guarantee that the server has processed above message. 15 | await nc.flush(timeout=1) 16 | 17 | # [end flush] 18 | 19 | await nc.close() 20 | 21 | loop = asyncio.get_event_loop() 22 | loop.run_until_complete(example()) 23 | loop.close() 24 | -------------------------------------------------------------------------------- /max_payload.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin max_payload] 7 | nc = NATS() 8 | 9 | await nc.connect(servers=["nats://demo.nats.io:4222"]) 10 | 11 | print("Maximum payload is %d bytes" % nc.max_payload) 12 | 13 | # Do something with the max payload. 14 | 15 | # [end max_payload] 16 | 17 | await nc.close() 18 | 19 | loop = asyncio.get_event_loop() 20 | loop.run_until_complete(example()) 21 | loop.close() 22 | -------------------------------------------------------------------------------- /no_echo.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | # [begin no_echo] 6 | ncA = NATS() 7 | ncB = NATS() 8 | 9 | await ncA.connect(no_echo=True) 10 | await ncB.connect() 11 | 12 | async def handler(msg): 13 | # Messages sent by `ncA' will not be received. 14 | print("[Received] ", msg) 15 | 16 | await ncA.subscribe("greetings", cb=handler) 17 | await ncA.flush() 18 | await ncA.publish("greetings", b'Hello World!') 19 | await ncB.publish("greetings", b'Hello World!') 20 | 21 | # Do something with the connection 22 | 23 | await asyncio.sleep(1) 24 | await ncA.drain() 25 | await ncB.drain() 26 | 27 | # [end no_echo] 28 | 29 | loop = asyncio.get_event_loop() 30 | loop.run_until_complete(example()) 31 | loop.close() 32 | -------------------------------------------------------------------------------- /notapplicable.txt: -------------------------------------------------------------------------------- 1 | [begin reconnect_5mb] 2 | # Asyncio NATS client currently does not implement a reconnect buffer 3 | [end reconnect_5mb] 4 | 5 | [begin control_2k] 6 | # Asyncio NATS client does not allow custom control lines 7 | [end control_2k] 8 | 9 | [begin subscribe_sync] 10 | # Asyncio NATS client currently does not have a sync subscribe API 11 | [end subscribe_sync] 12 | 13 | [begin servers_added] 14 | # Asyncio NATS client does not support discovered servers handler right now 15 | [end servers_added] 16 | 17 | [begin connection_listener] 18 | # Asyncio NATS client can be defined a number of event callbacks 19 | async def disconnected_cb(): 20 | print("Got disconnected!") 21 | 22 | async def reconnected_cb(): 23 | # See who we are connected to on reconnect. 24 | print("Got reconnected to {url}".format(url=nc.connected_url.netloc)) 25 | 26 | async def error_cb(e): 27 | print("There was an error: {}".format(e)) 28 | 29 | async def closed_cb(): 30 | print("Connection is closed") 31 | 32 | # Setup callbacks to be notified on disconnects and reconnects 33 | options["disconnected_cb"] = disconnected_cb 34 | options["reconnected_cb"] = reconnected_cb 35 | 36 | # Setup callbacks to be notified when there is an error 37 | # or connection is closed. 38 | options["error_cb"] = error_cb 39 | options["closed_cb"] = closed_cb 40 | 41 | await nc.connect(**options) 42 | [end connection_listener] 43 | -------------------------------------------------------------------------------- /ping_20s.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin ping_20s] 7 | nc = NATS() 8 | 9 | await nc.connect( 10 | servers=["nats://demo.nats.io:4222"], 11 | # Set Ping Interval to 20 seconds 12 | ping_interval=20, 13 | ) 14 | 15 | # Do something with the connection. 16 | 17 | # [end ping_20s] 18 | 19 | while True: 20 | if nc.is_closed: 21 | break 22 | await asyncio.sleep(1) 23 | 24 | await nc.close() 25 | 26 | loop = asyncio.get_event_loop() 27 | loop.run_until_complete(example()) 28 | loop.close() 29 | -------------------------------------------------------------------------------- /ping_5.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin ping_5] 7 | nc = NATS() 8 | 9 | await nc.connect( 10 | servers=["nats://demo.nats.io:4222"], 11 | # Set maximum number of PINGs out without getting a PONG back 12 | # before the connection will be disconnected as a stale connection. 13 | max_outstanding_pings=5, 14 | ping_interval=1, 15 | ) 16 | 17 | # Do something with the connection. 18 | 19 | # [end ping_5] 20 | 21 | while True: 22 | if nc.is_closed: 23 | break 24 | await asyncio.sleep(1) 25 | 26 | await nc.close() 27 | 28 | loop = asyncio.get_event_loop() 29 | loop.run_until_complete(example()) 30 | loop.close() 31 | -------------------------------------------------------------------------------- /publish_bytes.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin publish_bytes] 7 | nc = NATS() 8 | 9 | await nc.connect(servers=["nats://demo.nats.io:4222"]) 10 | 11 | await nc.publish("updates", b'All is Well') 12 | 13 | # [end publish_bytes] 14 | 15 | await nc.close() 16 | 17 | loop = asyncio.get_event_loop() 18 | loop.run_until_complete(example()) 19 | loop.close() 20 | -------------------------------------------------------------------------------- /publish_json.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import json 3 | from nats.aio.client import Client as NATS 4 | 5 | async def example(): 6 | 7 | # [begin publish_json] 8 | nc = NATS() 9 | 10 | await nc.connect(servers=["nats://demo.nats.io:4222"]) 11 | 12 | await nc.publish("updates", json.dumps({"symbol": "GOOG", "price": 1200 }).encode()) 13 | 14 | # [end publish_json] 15 | 16 | await nc.close() 17 | 18 | loop = asyncio.get_event_loop() 19 | loop.run_until_complete(example()) 20 | loop.close() 21 | -------------------------------------------------------------------------------- /publish_with_reply.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import json 3 | from nats.aio.client import Client as NATS 4 | from nats.aio.utils import new_inbox 5 | 6 | async def example(): 7 | 8 | # [begin publish_with_reply] 9 | nc = NATS() 10 | 11 | future = asyncio.Future() 12 | 13 | async def sub(msg): 14 | nonlocal future 15 | future.set_result(msg) 16 | 17 | await nc.connect(servers=["nats://demo.nats.io:4222"]) 18 | await nc.subscribe("time", cb=sub) 19 | 20 | unique_reply_to = new_inbox() 21 | await nc.publish_request("time", unique_reply_to, b'') 22 | 23 | # Use the response 24 | msg = await asyncio.wait_for(future, 1) 25 | print("Reply:", msg) 26 | 27 | # [end publish_with_reply] 28 | 29 | await nc.close() 30 | 31 | loop = asyncio.get_event_loop() 32 | loop.run_until_complete(example()) 33 | loop.close() 34 | -------------------------------------------------------------------------------- /reconnect_10s.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | # [begin reconnect_10s] 6 | nc = NATS() 7 | await nc.connect( 8 | servers=["nats://demo.nats.io:4222"], 9 | reconnect_time_wait=10, 10 | ) 11 | 12 | # Do something with the connection 13 | 14 | await nc.close() 15 | 16 | # [end reconnect_10s] 17 | 18 | loop = asyncio.get_event_loop() 19 | loop.run_until_complete(example()) 20 | loop.close() 21 | -------------------------------------------------------------------------------- /reconnect_10x.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | # [begin reconnect_10x] 6 | nc = NATS() 7 | await nc.connect( 8 | servers=["nats://demo.nats.io:4222"], 9 | max_reconnect_attempts=10, 10 | ) 11 | 12 | # Do something with the connection 13 | 14 | await nc.close() 15 | 16 | # [end reconnect_10x] 17 | 18 | loop = asyncio.get_event_loop() 19 | loop.run_until_complete(example()) 20 | loop.close() 21 | -------------------------------------------------------------------------------- /reconnect_event.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin reconnect_event] 7 | nc = NATS() 8 | 9 | async def disconnected_cb(): 10 | print("Got disconnected!") 11 | 12 | async def reconnected_cb(): 13 | # See who we are connected to on reconnect. 14 | print("Got reconnected to {url}".format(url=nc.connected_url.netloc)) 15 | 16 | await nc.connect( 17 | servers=["nats://demo.nats.io:4222"], 18 | reconnect_time_wait=10, 19 | reconnected_cb=reconnected_cb, 20 | disconnected_cb=disconnected_cb, 21 | ) 22 | 23 | # Do something with the connection. 24 | 25 | # [end reconnect_event] 26 | 27 | while True: 28 | if nc.is_closed: 29 | break 30 | await asyncio.sleep(1) 31 | 32 | await nc.close() 33 | 34 | loop = asyncio.get_event_loop() 35 | loop.run_until_complete(example()) 36 | loop.close() 37 | -------------------------------------------------------------------------------- /reconnect_no_random.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | # [begin reconnect_no_random] 6 | nc = NATS() 7 | await nc.connect( 8 | servers=[ 9 | "nats://demo.nats.io:1222", 10 | "nats://demo.nats.io:1223", 11 | "nats://demo.nats.io:1224" 12 | ], 13 | dont_randomize=True, 14 | ) 15 | 16 | # Do something with the connection 17 | 18 | await nc.close() 19 | 20 | # [end reconnect_no_random] 21 | 22 | loop = asyncio.get_event_loop() 23 | loop.run_until_complete(example()) 24 | loop.close() 25 | -------------------------------------------------------------------------------- /reconnect_none.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | # [begin reconnect_none] 6 | nc = NATS() 7 | await nc.connect( 8 | servers=[ 9 | "nats://demo.nats.io:1222", 10 | "nats://demo.nats.io:1223", 11 | "nats://demo.nats.io:1224" 12 | ], 13 | allow_reconnect=False, 14 | ) 15 | 16 | # Do something with the connection 17 | 18 | await nc.close() 19 | 20 | # [end reconnect_none] 21 | 22 | loop = asyncio.get_event_loop() 23 | loop.run_until_complete(example()) 24 | loop.close() 25 | -------------------------------------------------------------------------------- /request_reply.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import json 3 | from nats.aio.client import Client as NATS 4 | from nats.aio.utils import new_inbox 5 | 6 | async def example(): 7 | 8 | # [begin request_reply] 9 | nc = NATS() 10 | 11 | async def sub(msg): 12 | await nc.publish(msg.reply, b'response') 13 | 14 | await nc.connect(servers=["nats://demo.nats.io:4222"]) 15 | await nc.subscribe("time", cb=sub) 16 | 17 | # Send the request 18 | try: 19 | msg = await nc.request("time", b'', timeout=1) 20 | # Use the response 21 | print("Reply:", msg) 22 | except asyncio.TimeoutError: 23 | print("Timed out waiting for response") 24 | 25 | # [end request_reply] 26 | 27 | await nc.close() 28 | 29 | loop = asyncio.get_event_loop() 30 | loop.run_until_complete(example()) 31 | loop.close() 32 | -------------------------------------------------------------------------------- /slow_listener.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import nats.aio.errors 3 | from nats.aio.client import Client as NATS 4 | 5 | async def example(): 6 | 7 | # [begin slow_listener] 8 | 9 | nc = NATS() 10 | 11 | async def error_cb(e): 12 | if type(e) is nats.aio.errors.ErrSlowConsumer: 13 | print("Slow consumer error, unsubscribing from handling further messages...") 14 | await nc.unsubscribe(e.sid) 15 | 16 | await nc.connect( 17 | servers=["nats://demo.nats.io:4222"], 18 | error_cb=error_cb, 19 | ) 20 | 21 | msgs = [] 22 | future = asyncio.Future() 23 | async def cb(msg): 24 | nonlocal msgs 25 | nonlocal future 26 | print(msg) 27 | msgs.append(msg) 28 | 29 | if len(msgs) == 3: 30 | # Head of line blocking on other messages caused 31 | # by single message proccesing taking long... 32 | await asyncio.sleep(1) 33 | 34 | await nc.subscribe("updates", cb=cb, pending_msgs_limit=5) 35 | 36 | for i in range(0, 10): 37 | await nc.publish("updates", "msg #{}".format(i).encode()) 38 | await asyncio.sleep(0) 39 | 40 | try: 41 | await asyncio.wait_for(future, 1) 42 | except asyncio.TimeoutError: 43 | pass 44 | 45 | for msg in msgs: 46 | print("[Received]", msg) 47 | 48 | await nc.close() 49 | 50 | # [end slow_listener] 51 | 52 | loop = asyncio.get_event_loop() 53 | loop.run_until_complete(example()) 54 | loop.close() 55 | -------------------------------------------------------------------------------- /sub_pending_limits.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin slow_pending_limits] 7 | nc = NATS() 8 | 9 | await nc.connect(servers=["nats://demo.nats.io:4222"]) 10 | 11 | future = asyncio.Future() 12 | 13 | async def cb(msg): 14 | nonlocal future 15 | future.set_result(msg) 16 | 17 | # Set limits of 1000 messages or 5MB 18 | await nc.subscribe("updates", cb=cb, pending_bytes_limit=5*1024*1024, pending_msgs_limit=1000) 19 | 20 | # [end slow_pending_limits] 21 | 22 | await nc.publish("updates", b'All is Well') 23 | await nc.flush() 24 | 25 | # Wait for message to come in 26 | msg = await asyncio.wait_for(future, 1) 27 | 28 | 29 | print(msg) 30 | 31 | await nc.close() 32 | 33 | loop = asyncio.get_event_loop() 34 | loop.run_until_complete(example()) 35 | loop.close() 36 | -------------------------------------------------------------------------------- /subscribe_arrow.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin subscribe_arrow] 7 | nc = NATS() 8 | 9 | await nc.connect(servers=["nats://demo.nats.io:4222"]) 10 | 11 | # Use queue to wait for 4 messages to arrive 12 | queue = asyncio.Queue() 13 | async def cb(msg): 14 | await queue.put(msg) 15 | 16 | await nc.subscribe("time.>", cb=cb) 17 | 18 | # Send 2 messages and wait for them to come in 19 | await nc.publish("time.A.east", b'A') 20 | await nc.publish("time.B.east", b'B') 21 | await nc.publish("time.C.west", b'C') 22 | await nc.publish("time.D.west", b'D') 23 | 24 | for i in range(0, 4): 25 | msg = await queue.get() 26 | print("Msg:", msg) 27 | 28 | await nc.close() 29 | 30 | # [end subscribe_arrow] 31 | 32 | loop = asyncio.get_event_loop() 33 | loop.run_until_complete(example()) 34 | loop.close() 35 | -------------------------------------------------------------------------------- /subscribe_async.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin subscribe_async] 7 | nc = NATS() 8 | 9 | await nc.connect(servers=["nats://demo.nats.io:4222"]) 10 | 11 | future = asyncio.Future() 12 | 13 | async def cb(msg): 14 | nonlocal future 15 | future.set_result(msg) 16 | 17 | await nc.subscribe("updates", cb=cb) 18 | await nc.publish("updates", b'All is Well') 19 | await nc.flush() 20 | 21 | # Wait for message to come in 22 | msg = await asyncio.wait_for(future, 1) 23 | 24 | # [end subscribe_async] 25 | print(msg) 26 | 27 | await nc.close() 28 | 29 | loop = asyncio.get_event_loop() 30 | loop.run_until_complete(example()) 31 | loop.close() 32 | -------------------------------------------------------------------------------- /subscribe_json.py: -------------------------------------------------------------------------------- 1 | # [begin subscribe_json] 2 | import asyncio 3 | import json 4 | from nats.aio.client import Client as NATS 5 | from nats.aio.errors import ErrTimeout 6 | 7 | async def run(loop): 8 | nc = NATS() 9 | 10 | await nc.connect(servers=["nats://127.0.0.1:4222"], loop=loop) 11 | 12 | async def message_handler(msg): 13 | data = json.loads(msg.data.decode()) 14 | print(data) 15 | 16 | sid = await nc.subscribe("updates", cb=message_handler) 17 | await nc.flush() 18 | 19 | await nc.auto_unsubscribe(sid, 2) 20 | await nc.publish("updates", json.dumps({"symbol": "GOOG", "price": 1200 }).encode()) 21 | await asyncio.sleep(1, loop=loop) 22 | await nc.close() 23 | # [end subscribe_json] 24 | 25 | if __name__ == '__main__': 26 | loop = asyncio.get_event_loop() 27 | loop.run_until_complete(run(loop)) 28 | loop.close() 29 | -------------------------------------------------------------------------------- /subscribe_queue.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin subscribe_queue] 7 | nc = NATS() 8 | 9 | await nc.connect(servers=["nats://demo.nats.io:4222"]) 10 | 11 | future = asyncio.Future() 12 | 13 | async def cb(msg): 14 | nonlocal future 15 | future.set_result(msg) 16 | 17 | await nc.subscribe("updates", queue="workers", cb=cb) 18 | await nc.publish("updates", b'All is Well') 19 | 20 | msg = await asyncio.wait_for(future, 1) 21 | print("Msg", msg) 22 | 23 | # [end subscribe_queue] 24 | 25 | await nc.close() 26 | 27 | loop = asyncio.get_event_loop() 28 | loop.run_until_complete(example()) 29 | loop.close() 30 | -------------------------------------------------------------------------------- /subscribe_star.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin subscribe_star] 7 | nc = NATS() 8 | 9 | await nc.connect(servers=["nats://demo.nats.io:4222"]) 10 | 11 | # Use queue to wait for 2 messages to arrive 12 | queue = asyncio.Queue() 13 | async def cb(msg): 14 | await queue.put_nowait(msg) 15 | 16 | await nc.subscribe("time.*.east", cb=cb) 17 | 18 | # Send 2 messages and wait for them to come in 19 | await nc.publish("time.A.east", b'A') 20 | await nc.publish("time.B.east", b'B') 21 | 22 | msg_A = await queue.get() 23 | msg_B = await queue.get() 24 | 25 | print("Msg A:", msg_A) 26 | print("Msg B:", msg_B) 27 | 28 | # [end subscribe_star] 29 | 30 | await nc.close() 31 | 32 | loop = asyncio.get_event_loop() 33 | loop.run_until_complete(example()) 34 | loop.close() 35 | -------------------------------------------------------------------------------- /subscribe_w_reply.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | from nats.aio.utils import new_inbox 4 | from datetime import datetime 5 | 6 | async def example(): 7 | 8 | # [begin subscribe_w_reply] 9 | nc = NATS() 10 | 11 | await nc.connect(servers=["nats://demo.nats.io:4222"]) 12 | 13 | future = asyncio.Future() 14 | 15 | async def cb(msg): 16 | nonlocal future 17 | future.set_result(msg) 18 | 19 | await nc.subscribe("time", cb=cb) 20 | 21 | await nc.publish_request("time", new_inbox(), b'What is the time?') 22 | await nc.flush() 23 | 24 | # Read the message 25 | msg = await asyncio.wait_for(future, 1) 26 | 27 | # Send the time 28 | time_as_bytes = "{}".format(datetime.now()).encode() 29 | await nc.publish(msg.reply, time_as_bytes) 30 | 31 | # [end subscribe_w_reply] 32 | 33 | await nc.close() 34 | 35 | loop = asyncio.get_event_loop() 36 | loop.run_until_complete(example()) 37 | loop.close() 38 | -------------------------------------------------------------------------------- /unsubscribe.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin unsubscribe] 7 | nc = NATS() 8 | 9 | await nc.connect(servers=["nats://demo.nats.io:4222"]) 10 | 11 | future = asyncio.Future() 12 | 13 | async def cb(msg): 14 | nonlocal future 15 | future.set_result(msg) 16 | 17 | sid = await nc.subscribe("updates", cb=cb) 18 | await nc.publish("updates", b'All is Well') 19 | 20 | # Remove interest in subject 21 | await nc.unsubscribe(sid) 22 | 23 | # Won't be received... 24 | await nc.publish("updates", b'...') 25 | 26 | # [end unsubscribe] 27 | 28 | await nc.close() 29 | 30 | loop = asyncio.get_event_loop() 31 | loop.run_until_complete(example()) 32 | loop.close() 33 | -------------------------------------------------------------------------------- /unsubscribe_auto.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin unsubscribe_auto] 7 | nc = NATS() 8 | 9 | await nc.connect(servers=["nats://demo.nats.io:4222"]) 10 | 11 | async def cb(msg): 12 | print(msg) 13 | 14 | sid = await nc.subscribe("updates", cb=cb) 15 | await nc.auto_unsubscribe(sid, 1) 16 | await nc.publish("updates", b'All is Well') 17 | 18 | # Won't be received... 19 | await nc.publish("updates", b'...') 20 | 21 | # [end unsubscribe_auto] 22 | 23 | await asyncio.sleep(1) 24 | 25 | await nc.close() 26 | 27 | loop = asyncio.get_event_loop() 28 | loop.run_until_complete(example()) 29 | loop.close() 30 | -------------------------------------------------------------------------------- /wildcard_tester.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from nats.aio.client import Client as NATS 3 | 4 | async def example(): 5 | 6 | # [begin wildcard_tester] 7 | nc = NATS() 8 | 9 | await nc.connect(servers=["nats://demo.nats.io:4222"]) 10 | 11 | await nc.publish("time.us.east", b'...') 12 | await nc.publish("time.us.east.atlanta", b'...') 13 | 14 | await nc.publish("time.eu.east", b'...') 15 | await nc.publish("time.eu.east.warsaw", b'...') 16 | 17 | await nc.close() 18 | 19 | # [end wildcard_tester] 20 | 21 | loop = asyncio.get_event_loop() 22 | loop.run_until_complete(example()) 23 | loop.close() 24 | --------------------------------------------------------------------------------