您的位置:首页 > 数据库 > Redis

tornado 异步客户端tornado-redis的使用

2017-03-30 22:58 417 查看
tornado 可用的异步 redis 客户端,使用很方便。

下面的例子介绍了怎么使用管道设置值和读取值的简单操作

#coding:utf-8
import tornadoredis
import tornado.httpserver
import tornado.web
import tornado.ioloop
import tornado.gen

#设置连接池
CONNECTION_POOL = tornadoredis.ConnectionPool(max_connections=500,wait_for_available=True)
# 生成一个客户端,这里并没有给出host和port,使用的默认的参数,我的redis使用默认的参数也可以连接上
# Client的参数为
# def __init__(self, host='localhost', port=6379, unix_socket_path=None,
#                  password=None, selected_db=None, io_loop=None,
#                  connection_pool=None):
c = tornadoredis.Client(connection_pool=CONNECTION_POOL)

class MainHandler(tornado.web.RequestHandler):

@tornado.web.asynchronous
@tornado.gen.engine
def get(self):
name = yield tornado.gen.Task(c.get,'name')
age = yield tornado.gen.Task(c.get,'age')
height = yield tornado.gen.Task(c.get,'height')
self.finish("name: {0} age: {1} height: {2}".format(name, age, height))

application = tornado.web.Application([
(r'/', MainHandler),
])

@tornado.gen.engine
def create_test_data():
c = tornadoredis.Client()
# 使用管道设置值
with c.pipeline() as pipe:
pipe.set('name', 'zhangsan')
pipe.set('age', '10')
pipe.set('height', '1.8')
yield tornado.gen.Task(pipe.execute)

if __name__ == '__main__':
# Start the data initialization routine
create_test_data()
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
print 'Demo is runing at 0.0.0.0:8888\nQuit the demo with CONTROL-C'
tornado.ioloop.IOLoop.instance().start()


执行结果

name: zhangsan age: 10 height: 1.8


1、scan的使用

yield tornado.gen.Task(c.scan, cursor = 0, match = "*:{0}".format(sha1))


2、incr的使用

tornado.gen.Task(async.incr, 'file_upload_idx')


3、hmget的使用

yield tornado.gen.Task(async.hmget,key,["uid","file_type"])


注意

在使用tornado-redis的时候一定要在形如class MainHandler(tornado.web.RequestHandler)中使用,不要想着脱离它再使用,否则会出现很多的错误,这个坑我已经踩过了,大家注意,如果在其他的地方使用可以选择使用redis这个包。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  tornado redis 异步
相关文章推荐