各位大大好,
小弟目前有多個獨立python執行程式 & django server,
有一隻py程式會發佈訊息,其餘各個執行程式 & server需要接收訊息,
目前使用Redis做中間溝通,在獨立的python能夠正常執行,
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Variables definition
import json
import sys
import time
import redis
REDIS_SERVER_CONF = {
'servers': {
'main_server': {
'HOST': '127.0.0.1',
'PORT': 6379,
'DATABASE': 11
}
}
}
class RedisWrapper():
shared_state = {}
def __init__(self):
self.__dict__ = self.shared_state
def redis_connect(self, server_key):
redis_server_conf = REDIS_SERVER_CONF['servers'][server_key]
connection_pool = redis.ConnectionPool(host=redis_server_conf['HOST'], port=redis_server_conf['PORT'],
db=redis_server_conf['DATABASE'])
return redis.StrictRedis(connection_pool=connection_pool)
if __name__ == "__main__":
import random
r_server = RedisWrapper().redis_connect(server_key='main_server')
seeds = {
"EMMA1": 'J7-21-01-065',
"EMMA2": 'J7-21-01-067',
"EMMA3": 'J7-21-01-063_1',
"EMMA4": 'J7-21-01-129_1',
"EMMA5": ''
}
while True:
try:
print("SEND")
wipSeed = random.choice(list(seeds.keys()))
sleepTime = random.randint(3, 9)
data = {
'wip': wipSeed,
'materialname': seeds[wipSeed]
}
r_server.publish(
'Share_News',
json.dumps(data)
)
print("SEND CH:{} MSG:{}".format('Share_News', data))
time.sleep(sleepTime)
except KeyboardInterrupt:
sys.exit(0)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Variables definition
import json
import sys
import threading
import redis
REDIS_SERVER_CONF = {
'servers': {
'main_server': {
'HOST': '127.0.0.1',
'PORT': 6379,
'DATABASE': 11
}
}
}
class RedisWrapper():
shared_state = {}
def __init__(self):
self.__dict__ = self.shared_state
def redis_connect(self, server_key):
redis_server_conf = REDIS_SERVER_CONF['servers'][server_key]
connection_pool = redis.ConnectionPool(host=redis_server_conf['HOST'], port=redis_server_conf['PORT'],
db=redis_server_conf['DATABASE'])
return redis.StrictRedis(connection_pool=connection_pool)
def redis_sub(r_server):
print("WAIT RECEIVE")
sub = r_server.pubsub()
sub.subscribe('Share_News')
for message in sub.listen():
print(message)
if (message.get("type") == "message"):
data = json.loads(message.get("data"))
print("RECEIVE CH:{} MSG:{}".format(
data.get("wip"), data.get("materialname")))
if __name__ == "__main__":
r_server = RedisWrapper().redis_connect(server_key='main_server')
try:
processW1 = threading.Thread(
target=redis_sub, args=(r_server, ))
processW1.setDaemon(True)
processW1.start()
while (True):
pass
except KeyboardInterrupt:
sys.exit(0)
以上小弟目前已經能夠將獨立的python做溝通,
但如果接收或發送的對象是django呢?
該如何啟動服務?
在請各位大大賜教,感謝感謝!!