簡短截說闡述redis中事務的使用

原文轉載自「劉悅的技術博客」v3u.cn/a_id_127python

咱們知道,在關係型數據庫中,好比mysql,若是要使用事務,首先向數據庫服務器發送 BEGIN ,而後執行各個相互一致的寫操做和讀操做,最後,用戶能夠選擇發送 COMMIT 來確認以前所作的修改,或者發送 ROLLBACK 來放棄那些修改。mysql

一樣, Redis 中也有簡單的方法處理一連串相互一致的讀操做和寫操做。首先是以 MULTI 命令開始事務,後續跟着一連串命令,最後以 EXEC 結束事務或者以 DISCARD 命令撤銷全部命令並結束事務。redis

可是redis事務和mysql事務最重要的一點區別是,redis事務無論指令正確或者錯誤,都會執行,中途碰見錯誤指令也會繼續執行後面的指令,Redis並無像mysql那樣的事務回滾機制。mysql事務中若是執行過程當中發生了錯誤不只後面的sql語句不會執行,還會進行數據回滾,這是兩者事務的最大區別。Redis的事務出錯須要開發人員本身進行數據回滾等操做。sql

在翻閱了redis官方手冊之後,官方對此的解釋是:If you have a relational databases background, the fact that Redis commands can fail during a transaction, but still Redis will execute the rest of the transaction instead of rolling back, may look odd to you. However there are good opinions for this behavior:
Redis commands can fail only if called with a wrong syntax (and the problem is not detectable during the command queueing), or against keys holding the wrong data type: this means that in practical terms a failing command is the result of a programming errors, and a kind of error that is very likely to be detected during development, and not in production.
Redis is internally simplified and faster because it does not need the ability to roll back.
An argument against Redis point of view is that bugs happen, however it should be noted that in general the roll back does not save you from programming errors. For instance if a query increments a key by 2 instead of 1, or increments the wrong key, there is no way for a rollback mechanism to help. Given that no one can save the programmer from his or her errors, and that the kind of errors required for a Redis command to fail are unlikely to enter in production, we selected the simpler and faster approach of not supporting roll backs on errors.數據庫

大白話的意思就是:redis的做者認爲,當事務的執行時,通常發生錯誤都是由於業務編程錯誤形成的,這種錯誤一般只會出如今開發環境中,而基本不多會在實際的生產環境中出現(由於這種業務錯誤都會在測試的時候消滅),因此他認爲沒有必要爲 Redis 開發事務自動回滾功能,這和Redis追求的簡單高效的設計主旨不符合。編程

而mysql偏偏相反,mysql認爲數據庫有必要也有責任處理事務中報錯的狀況,因此mysql有自動回滾的功能。bash

在redis中使用事務:服務器

liuyue:~ liuyue$ redis-cli
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set test 123
QUEUED
127.0.0.1:6379> exec
1) OK
127.0.0.1:6379> get test
"123"
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set test 456
QUEUED
127.0.0.1:6379> discard
OK
127.0.0.1:6379> get test
"123"
127.0.0.1:6379> 
liuyue:~ liuyue$ clear 
複製代碼

在python中操做redis事務app

#導包
import redis

#定義ip
host = 'localhost'

#創建服務鏈接

r = redis.Redis(host=host)
pipe = r.pipeline()

#開啓事務
pipe.multi()
#存儲子命令
pipe.set('key2', 4)
#執行事務
pipe.execute()

print(r.get('key2'))
複製代碼

相關講解視頻:ide

www.bilibili.com/video/av932…

原文轉載自「劉悅的技術博客」 v3u.cn/a_id_127

相關文章
相關標籤/搜索