if __name__=="__main__":
# print ("yes")
# c = CrazyRedis()
# c.lpush("b","v")
# print ("yes")
#
pool = redis.ConnectionPool(host=host, port=6379, db=0)
r = redis.Redis(connection_pool=pool)
try:
dbconn = pymysql.connect(
host="127.0.0.1",
port=3306,
user="root",
password="123456",
database='ooxx',
)
except Exception as e:
print(u'初始化数据连接失败:%s' % e)
sys.exit()
# 执行签到
try:
print("id=====%s" % id)
db_cursor = dbconn.cursor()
print("id=====%s" % id)
for id in range(1, 6):
db_cursor.execute(
'UPDATE tb_signin_rank SET signin_num = signin_num + 1, signin_time = NOW(), gold_coin = gold_coin + (1 + RAND()*9) WHERE id = %s',
(id,))
db_cursor.execute('commit')
# 更新缓存
print("id=====%s"%id)
r.zincrby("tb_signin_rank:id:signin_num", id, 1)
except Exception as e:
print(u'执行数据库更新操作失败:%s' % e)
db_cursor.execute('rollback')
db_cursor.close()
exit()
# 展示用户签到次数
for id in range(1, 6):
result = r.zscore('tb_signin_rank:id:signin_num', id)
if not result: # 不存在缓存,从数据库读取
print(u'----从数据库读取用户签到次数----')
try:
db_cursor = dbconn.cursor()
db_cursor.execute('SELECT signin_num FROM tb_signin_rank WHERE id = %s', (id,))
result = db_cursor.fetchone()[0]
# 更新到缓存
r.zadd('tb_signin_rank:id:signin_num', id, result)
except Exception as e:
print(u'执行数据库查询操作失败:%s' % e)
db_cursor.close()
else: # 存在缓存,从缓存读取
print(u'----从缓存读取用户签到次数----')
result = int(result)
print(u'sigin_num of user[id=%s]: %s' % (id, result))
# 展示签到排行榜
result = r.zrevrange('tb_signin_rank:id:signin_num', 0, 10)
print(u'签到排行榜:')
print(result)结果打印:----从缓存读取用户签到次数----
sigin_num of user[id=1]: 1
----从缓存读取用户签到次数----
sigin_num of user[id=2]: 1
----从缓存读取用户签到次数----
sigin_num of user[id=3]: 1
----从缓存读取用户签到次数----
sigin_num of user[id=4]: 1
----从缓存读取用户签到次数----
sigin_num of user[id=5]: 18
签到排行榜:
['1', '2', '3', '4', '5']参考:http://blog.sina.com.cn/s/blog_13cc013b50102wb5w.html