基於python+mysql+redis緩衝設計與資料庫關聯資料處理

來源:互聯網
上載者:User

標籤: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緩衝設計與資料庫關聯資料處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.