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