0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MongoDBによる多言語間非同期通信

Last updated at Posted at 2019-02-02

#目的

オンライン学習システムを開発時、システム各部分を違う言語で開発し、
データ交信の手段としてMongoDBが有効です。

#MongoDBの導入

下記記事をご参照ください。
個人的にはMongoDB Compass よりRobo 3T が使いやすいと感じています。

#MongoDBの設計

本例では下記のようにDBを作成する。
cmdに入るデータはjavaとか他言語により書き込まれる動作指示です。
responseには他言語への学習結果報告です。
image.png

#学習本体

train.py

from pymongo import MongoClient
import sys
import time
break_flag = False
end_flag = False

client = MongoClient('localhost', 27017)
db = client.j_p

def train(epoch):
    global break_flag,end_flag
    for e in range(epoch):
        #通常train
        print("in train")
        #Train結果を上のレーヤへ送信
        resp = db.cmd_respons.find_one ({"_id":"5c4be3e86b95412bca9230a6"})
        old_resp = resp["response"]
        new_resp = 890 #疑似結果
        db.cmd_respons.update_one({'response': old_resp},
                        {'$set': {'response': new_resp}})
        if (break_flag == True):
            print("break in train.py ")
            #sys.stdout.flush()           
            break
    end_flag = True
    print("exit in train.py")
    time.sleep(2)

#学習制御

control.py
from pymongo import MongoClient
import train
import threading
import time
client = MongoClient('localhost', 27017)
db = client.j_p
epoch = 100000
def control():
    cmd = db.cmd_respons.find_one({"_id":"5c4be3c56b95412bca923099"})
    if(cmd["cmd"] == "start"):
        #Trainを起動する
        thread = threading.Thread(target=train.train, args=(epoch,))
        thread.daemon = True
        thread.start()
    while True:
        #上のレーヤと交信
        cmd = db.cmd_respons.find_one({"_id":"5c4be3c56b95412bca923099"})
        if(cmd["cmd"] == "stop"):
            train.break_flag = True
            print("break by stop command")
            time.sleep(2)
            break
        if train.end_flag == True:
            break
    
    time.sleep(2)
    print("exit in control.py")

    
if __name__ == '__main__':
    control()

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?