龙卷风Web和线程

时间:2011-10-21 07:32:57

标签: python tornado

我是Tornado和Python Threads的新手。我想要实现的目标如下: 我有一个Tornado Web服务器,它接收用户的请求。我想在本地存储一些数据,并将其作为批量插入定期写入数据库。

import tornado.ioloop
import tornado.web
import threading

# Keep userData locally in memory
UserData = {}

def background(f):
    """
    a threading decorator
    use @background above the function you want to thread
    (run in the background)
    """
    def bg_f(*a, **kw):
        threading.Thread(target=f, args=a, kwargs=kw).start()
    return bg_f

@background
def PostRecentDataToDBThread(iter = -1):
    i = 0
    while iter == -1 or i < iter: 
        #send data to DB
        UserData = {}
        time.sleep(5*60)
        i = i + 1

class AddHandler(tornado.web.RequestHandler):
    def post(self):
        userID = self.get_argument('ui')
        Data = self.get_argument('data')

        UserData[userID] = Data 


if __name__ == "__main__":
    tornado.options.parse_command_line()

    print("start PostRecentDataToDBThread")
    ### Here we start a thread that periodically sends data to the data base.
    ### The thread is called every 5min. 
    PostRecentDataToDBThread(-1)

    print("Started tornado on port: %d" % options.port)

    application = tornado.web.Application([
        (r"/", MainHandler),
        (r"/add", AddHandler)
    ])
    application.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

这是实现目标的好方法吗?我想最小化服务器阻塞时间。或者我应该使用gevent或其他什么?我可以通过从Tornado和线程访问UserData来遇到问题吗?只要没有服务器崩溃,数据一致性就不那么重要了。

1 个答案:

答案 0 :(得分:7)

Tornado不适用于多线程。它基于epoll在代码的不同部分之间切换上下文。

一般情况下,我建议通过消息队列将数据发送到单独的工作进程(如pika + RabbitMQ,它与Tornado集成得非常好)。工作进程可以使用数据累积消息并将它们批量写入数据库,或者您可以使用此设置实现任何其他数据处理逻辑。

或者,您可以使用带有brukva的Redis将传入数据异步写入内存数据库,然后根据Redis配置将其异步转储到磁盘。