feat: python接入nats
This commit is contained in:
parent
67b3943dc4
commit
743d2ef1d0
|
@ -1,22 +1,22 @@
|
|||
from flask import Flask, request, jsonify
|
||||
import nats.aio.client
|
||||
import asyncio
|
||||
from flask import Flask, jsonify
|
||||
from pynats2 import NATSClient
|
||||
import json
|
||||
|
||||
app = Flask(__name__)
|
||||
nc = nats.aio.client.Client()
|
||||
|
||||
@app.route('/send_to_nats', methods=['POST'])
|
||||
def send_to_nats():
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
loop.run_until_complete(send_message(request.json))
|
||||
print("1")
|
||||
return 111
|
||||
@app.route('/publish', methods=['POST'])
|
||||
def publish_to_nats():
|
||||
data_dict = {
|
||||
"key": "value",
|
||||
"number": 123,
|
||||
"list": [1, 2, 3]
|
||||
}
|
||||
data_str = json.dumps(data_dict)
|
||||
# 将字符串转换为bytes
|
||||
data_bytes = data_str.encode('utf-8')
|
||||
with NATSClient() as client:
|
||||
client.publish("alg.test", payload=data_bytes)
|
||||
return jsonify({'message': 'Message sent successfully!'})
|
||||
|
||||
async def send_message(message):
|
||||
await nc.connect(servers=["nats://localhost:4222"])
|
||||
await nc.publish(jsonify({"cmd": "alg.test"}), str(message).encode())
|
||||
await nc.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True)
|
||||
|
|
|
@ -1,2 +1,2 @@
|
|||
flask
|
||||
asyncio-nats-client
|
||||
pynats2
|
|
@ -30,8 +30,9 @@ export class AppController {
|
|||
return 'ok';
|
||||
}
|
||||
|
||||
@EventPattern({ cmd: 'alg.test' })
|
||||
@EventPattern('alg.test')
|
||||
async algTest(payload) {
|
||||
return 'ok';
|
||||
console.log('来自: alg.test', payload);
|
||||
return payload;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user