標籤:mysql redis python
1、添加表
CREATE TABLE tb_signin(
id INT,
user_name VARCHAR(10),
signin_num INT ,
signin_time DATETIME ,
gold_coin INT
);
INSERT INTO tb_signin
VALUES(1, ‘ma‘, 0, NULL, 0),
(2, ‘he‘, 0, NULL, 0),
(3, ‘yu‘, 0, NULL, 0),
(4, ‘hai‘, 0, NULL, 0),
(5, ‘fang‘, 0, NULL, 0);
2、redis緩衝索引值設計
key value
表名:主索引值:列名 列值
或者:
表名:主索引值:列值1:列名1
樣本:把id為1的人的簽到次數(假設為5)儲存到redis中則可如下操作:
set(‘tb_signin_rank:1:signin_num‘, 5)
類似資料庫一樣,通過主鍵便可擷取其它值
3、redis關聯資料庫的資料處理模式:
,先判斷是否存在緩衝(通常是根據key),如果存在則從緩衝讀取,否則從資料庫讀取並更新緩衝
650) this.width=650;" src="http://s2.51cto.com/wyfs02/M02/89/A9/wKiom1gZXwHAkZyoAABDYTBtdJQ407.png-wh_500x0-wm_3-wmp_4-s_1933037467.png" title="redis1.png" alt="wKiom1gZXwHAkZyoAABDYTBtdJQ407.png-wh_50" />
適用情境:對資料即時性要求不高,更新比較不頻繁
如,先寫入redis然後,利用守護進程等方式,定時寫入到資料庫
650) this.width=650;" src="http://s5.51cto.com/wyfs02/M02/89/A7/wKioL1gZXxrDQ2YNAAA9dIkMOCY732.png-wh_500x0-wm_3-wmp_4-s_1440030602.png" title="red2.png" alt="wKioL1gZXxrDQ2YNAAA9dIkMOCY732.png-wh_50" />
如,先寫入資料庫,然後再更新到緩衝
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/89/A7/wKioL1gZXyyy5XkAAAAy6gz0EKM820.png-wh_500x0-wm_3-wmp_4-s_1287887528.png" title="red3.png" alt="wKioL1gZXyyy5XkAAAAy6gz0EKM820.png-wh_50" />
####
import ConfigParserimport sysimport redisimport MySQLdb__name__ ==: pool=redis.ConnectionPool(=,=,=) r=redis.Redis(=pool) config=ConfigParser.ConfigParser() : dbcon=MySQLdb.connect(=,=,=,=,=,=) MySQLdb.Error,e: ,e sys.exit() : db_cursor=dbcon.cursor() id (,): db_cursor.execute(,id) db_cursor.execute() r.zincrby(, id, ) e: (% e) db_cursor.execute() db_cursor.close() () id (,): result=r.zscore(,id) result: : db_cursor=dbcon.cursor() db_cursor.execute(,id) result=db_cursor.fetchone()[] r.zadd(,id,result) e: % e db_cursor.close() : () result = (result) (% (id, result))
###
zadd:命令用於將一個或多個成員元素及其分數值加入到有序集當中
zscore:命令返回成員的有序集合在鍵比分。如果成員沒有在排序集合存在,或鍵不存在,則返回nil。
本文出自 “DBSpace” 部落格,請務必保留此出處http://dbspace.blog.51cto.com/6873717/1868400
基於python+mysql+redis緩衝設計與資料庫關聯資料處理