Redis事务操作

2020-12-19  本文已影响0人  攻城老狮

事务

  1. 正常事务
127.0.0.1:6379> multi # 开启事务
OK
127.0.0.1:6379> set name yorick # 命令依此入队
QUEUED
127.0.0.1:6379> set age 23
QUEUED
127.0.0.1:6379> get name
QUEUED
127.0.0.1:6379> set address beijing
QUEUED
127.0.0.1:6379> exec # 执行事务
1) OK
2) OK
3) "yorick"
4) OK
  1. 放弃事务
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set name yorick
QUEUED
127.0.0.1:6379> set age 23
QUEUED
127.0.0.1:6379> discard # 放弃事务
OK
  1. 命令语法错误(编译性错误)
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set name yorick
QUEUED
127.0.0.1:6379> set age # 命令语法错误
(error) ERR wrong number of arguments for 'set' command
127.0.0.1:6379> set address beijing
QUEUED
127.0.0.1:6379> exec # 全部命令均不会执行
(error) EXECABORT Transaction discarded because of previous errors.
  1. 执行中遇到错误(运行时错误)
127.0.0.1:6379> set name yorick
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set address beijing
QUEUED
127.0.0.1:6379> incr name # 运行时出错
QUEUED
127.0.0.1:6379> set height 181
QUEUED
127.0.0.1:6379> exec
1) OK
2) (error) ERR value is not an integer or out of range
3) OK
127.0.0.1:6379> get height # 其他命令均可被正常执行
"181"

监控

  1. 正常执行
127.0.0.1:6379> set money 100
OK
127.0.0.1:6379> set output 0
OK
127.0.0.1:6379> watch money # 监控money数据
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> decrby money 10
QUEUED
127.0.0.1:6379> incrby output 10
QUEUED
127.0.0.1:6379> exec # 正常执行,未有其他线程更改money数据
1) (integer) 90
2) (integer) 10
  1. 多线程修改值,乐观锁操作
127.0.0.1:6379> set money 100
OK
127.0.0.1:6379> set output 0
OK
127.0.0.1:6379> watch money # 监控
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> decrby money 20
QUEUED
127.0.0.1:6379> incrby output 20
QUEUED
127.0.0.1:6379> exec # 此时另外一个线程修改了money的值,导致更改失败
(nil)
127.0.0.1:6379> get money # 发现此时money值未被修改
"1000"
127.0.0.1:6379> get output
"0"

参考地址:https://www.bilibili.com/video/BV1S54y1R7SB

上一篇下一篇

猜你喜欢

热点阅读