使用 gcloud 的 Pub/Sub 將接收到的資料註冊到 Redis 中

在下一个订阅中,仅仅是将接收到的数据显示在屏幕上,但是现在改为将接收到的数据注册到 Redis 中。
使用 Python3 执行 gcloud 的 Pub/Sub。

#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#   iot_subscribe_redis.py
#
#                       Feb/08/2018
# ------------------------------------------------------------------
import  sys 
import  json
import  redis
from google.cloud import pubsub
# ------------------------------------------------------------------
def to_redis_proc(json_str):
    sys.stderr.write("*** to_redis_proc *** start ***\n")
    rr = redis.Redis(host='localhost', port=6379, db=0)
    rec = json.loads(json_str)
    key = rec['data']['publish_time']
    sys.stderr.write("\tkey = " + str(key) + "\n")
    json_str_out = json.dumps(rec['data'])
    rr.set(key, json_str_out)
    sys.stderr.write("*** to_redis_proc *** end ***\n")
# ------------------------------------------------------------------
def callback(message):
    json_str = message.data.decode('utf8')
#
    to_redis_proc(json_str)
#
    message.ack()
#
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
subscriber = pubsub.SubscriberClient()

sub_name = 'projects/my-project-sep-10-2017/subscriptions/subscription_1'

subscription = subscriber.subscribe(sub_name)

future = subscription.open(callback)

try:
    try:
        future.result()
    except Exception as ex:
        subscription.close()
        sys.stderr.write(str(ex) + "\n")
except KeyboardInterrupt:
    sys.stderr.write('*** interrupted! ***\n')
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

执行脚本

export GOOGLE_APPLICATION_CREDENTIALS="./my-project-sep-10-2017.json"
./iot_subscribe_redis.py

需要发布以下数据。

{
  "data": {
    "id_raspberry": "tulip001",
    "sw0": 0,
    "sw1": 1,
    "sw2": 0,
    "sw3": 1,
    "tp0": 18.3,
    "tp1": 17.8,
    "vl0": 2.8,
    "vl1": 3.2,
    "publish_time": 20180208163531,
    "comment": "テスト 2月8日"
  }
}
广告
将在 10 秒后关闭
bannerAds