Basic Tutorials of Redis(8) -Transaction
Data play an important part in our project,how can we ensure correctness of the data and prevent the data
from error.In relational database, we are famillar with the usage of transaction.
begin
opreations
commit/rollback
But there are some differences between the Redis and relational database.Let's introduce the commands
first.There are only 5 commands to use while you use the transaction in redis.
I want to take an example to show you how to use the transaction.So here is the backgroud.There are three
persons and they want to buy the apple from the shop.The key for buying apple is the amount.
For this example,I use the hash to store the infomation of the users and the products.I use the string to store
the totalmoney for the trade.The following picture shows this example's initial data.
Let's start to finish this example.The first step is to initialize the data.
hmset user- name tom money
hmset user- name jack money
hmset user- name paul money
hmset product- name apple price amount
set totalmoney
Tom wants to buy the apple,so the product-1's amount should decrease by one,tom's money should decrease
by 150 and the totalmoney should increase by 150.The action buy includes three steps.We should check up the
product-1 with buy action.
watch product-
multi
hincrby product- amount -
hincrby user- money -
incrby totalmoney
exec
You will find that after the command multi ,the commands before exec all return queued.It means that those
commands store in a queue.After exec command,the client send this queue to the server and execute the commands.
But this is a normal situation that the amount is not changed before the transaction execute.
this,we need another client to imitate paul takes first.Before execute the transaction of jack's action,we decrease the
amount of product-1 to imitate paul buy the apple first.After executing the transaction of jack's action,the client returns
(nil) meaning the transaction of jack's action executed fail and the three commands didn't execute too.
This example shows the basic usage of transaction in redis.It is suitable for many questions.
execute the command exec will return an error.Because the multi didn't exists in this session.
Now I will show you how to use the transaction in StackExchange.Redis.
//Initiate the data
db.HashSet("user-1", new HashEntry[] { new HashEntry("name", "tom"), new HashEntry("money", ) });
db.HashSet("user-2", new HashEntry[] { new HashEntry("name", "jack"), new HashEntry("money", ) });
db.HashSet("user-3", new HashEntry[] { new HashEntry("name", "paul"), new HashEntry("money", ) });
db.HashSet("product-1", new HashEntry[] { new HashEntry("name", "apple"), new HashEntry("price", ),new HashEntry("amount", ) });
db.StringSet("totalmoney", ); //multi
var tran = db.CreateTransaction();
//watch
tran.AddCondition(Condition.HashEqual("product-1", "amount", "")); tran.HashDecrementAsync("product-1", "amount");
tran.HashDecrementAsync("user-1", "money", );
tran.StringIncrementAsync("totalmoney", ); Console.WriteLine(string.Format("execute the transaction {0}!", tran.Execute() ? "Y" : "N")); //multi
var tran2 = db.CreateTransaction();
//watch
tran.AddCondition(Condition.HashEqual("product-1", "amount", "")); tran.HashDecrementAsync("product-1", "amount");
tran.HashDecrementAsync("user-2", "money", );
tran.StringIncrementAsync("totalmoney", ); //paul take first
db.HashDecrement("product-1", "amount"); Console.WriteLine(string.Format("execute the transaction {0}!", tran.Execute() ? "Y" : "N"));
Debuging the code ,you will see the result as follow.
Basic Tutorials of Redis(8) -Transaction的更多相关文章
- Basic Tutorials of Redis(9) -First Edition RedisHelper
After learning the basic opreation of Redis,we should take some time to summarize the usage. And I w ...
- Basic Tutorials of Redis(7) -Publish and Subscribe
This post is mainly about the publishment and subscription in Redis.I think you may subscribe some o ...
- Basic Tutorials of Redis(2) - String
This post is mainly about how to use the commands to handle the Strings of Redis.And I will show you ...
- Basic Tutorials of Redis(6) - List
Redis's List is different from C#'s List,but similar with C#'s LinkedList.Sometimes I confuse with t ...
- Basic Tutorials of Redis(5) - Sorted Set
The last post is mainly about the unsorted set,in this post I will show you the sorted set playing a ...
- Basic Tutorials of Redis(4) -Set
This post will introduce you to some usages of Set in Redis.The Set is a unordered set,it means that ...
- Basic Tutorials of Redis(3) -Hash
When you first saw the name of Hash,what do you think?HashSet,HashTable or other data structs of C#? ...
- Basic Tutorials of Redis(1) - Install And Configure Redis
Nowaday, Redis became more and more popular , many projects use it in the cache module and the store ...
- JDBC Tutorials: Commit or Rollback transaction in finally block
http://skeletoncoder.blogspot.com/2006/10/jdbc-tutorials-commit-or-rollback.html JDBC Tutorials: Com ...
随机推荐
- Convert BSpline Curve to Arc Spline in OpenCASCADE
Convert BSpline Curve to Arc Spline in OpenCASCADE eryar@163.com Abstract. The paper based on OpenCA ...
- Android带加减的edittext
看了网上这样自带加减的edittext写得好复杂,还有各种监听事件,我觉得没有必有.于是我自己写了一个. 我这个edittext仅仅限制整数,每次加减1. public class TestEditT ...
- C#~异步编程再续~await与async引起的w3wp.exe崩溃-问题友好的解决
返回目录 关于死锁的原因 理解该死锁的原因在于理解await 处理contexts的方式,默认的,当一个未完成的Task 被await的时候,当前的上下文将在该Task完成的时候重新获得并继续执行剩余 ...
- 简单分析JavaScript中的面向对象
初学JavaScript的时候有人会认为JavaScript不是一门面向对象的语言,因为JS是没有类的概念的,但是这并不代表JavaScript没有对象的存在,而且JavaScript也提供了其它的方 ...
- Git(1)
安装Git 完毕 (在开始菜单打开的话,打开的不是你想要的路径,切换路径很麻烦) 1.D盘新建 GitTest 文件夹 2.打开GitTest , 在空白的地方右键, 3.单击 Git Bash He ...
- U盘安装Kali 出现cd-rom无法挂载 已解决
用U盘安装Kali Linux的过程中,出现cd-rom无法挂载的现象,百度坑比啊,醉了.下面亲测成功 出现无法挂载后,选择执行shell 第一步:df -m此时会看到挂载信息,最下面的是/dev/* ...
- linux上使用google身份验证器(简版)
系统:centos6.6 下载google身份验证包google-authenticator-master(其实只是一个.zip文件,在windwos下解压,然后传进linux) #cd /data/ ...
- 【python之路4】循环语句之while
1.while 循环语句 #!/usr/bin/env python # -*- coding:utf-8 -*- import time bol = True while bol: print '1 ...
- Linux服务器安全配置
众所周知,网络安全是一个非常重要的课题,而服务器是网络安全中最关键的环节.Linux被认为是一个比较安全的Internet服务器,作为一种开放源代码操作系统,一旦Linux系统中发现有安全漏洞,Int ...
- 微信小程序开发初探
一.关于微信小程序 1.1 小程序诞生的背景 张小龙说道: (1)一切以用户价值为依归→用户是微信的核心,所以微信中没有很多与客户无关的功能,比如QQ中的乱七八糟一系列东西. (2)让创造发挥价值→所 ...