iT邦幫忙

0

django 如何訂閱Redis訊息

各位大大好,
小弟目前有多個獨立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呢?
該如何啟動服務?

在請各位大大賜教,感謝感謝!!

看更多先前的討論...收起先前的討論...
froce iT邦大師 1 級 ‧ 2021-04-29 08:02:42 檢舉
https://github.com/sebleier/django-redis-cache/
不知道是不是你要的
回froce大大, 可能我描述得不太清楚,
我主要需要django能夠與獨立python應用程式溝通,

有找到解決方案正在了解當中,
https://medium.com/@master.rta/create-a-publish-subscriber-service-along-side-with-django-ed5337cb2bfb

感謝您!!
sma739146 iT邦新手 5 級 ‧ 2021-04-30 09:08:27 檢舉
Django 開一個 UrlApi 讓 redis requests 過去這樣不行嗎?
回sma739146大大,會使用這種溝通方式主要是因為會有較平凡的溝通,
所以目前選擇的方案有 訂閱/發佈模式 以及 webSocket模式,
來減少傳遞上所需要的一些動作。

感謝您!!

尚未有邦友回答

立即登入回答