ways to implement transactionsmulti (Open transaction) +exec (commit) +discard (Discard transaction) +watch (CAS optimistic lock) Lua script
the characteristics of Redis affairsAll methods in a transaction are executed serially, the execution is not interrupted by another client; the transaction is atomic, the command is executed entirely, or none is executed, but the atomicity of the Redis is inconsistent with the atomicity of the relational database, Redis Although the command is guaranteed to execute completely, but if a command fails at execution, Redis ignores it and continues with the next command.
error handling in a transactionSyntax error or system error: For this type of error, it can be found before a client executes a transaction (a successful commit in a transaction returns queued), and most of the client chooses to discard the transaction. Starting with Redis2.6.5, the server will record such errors at the client exec times and automatically discard the transaction; the execution times is wrong: The server ignores the error of the statement and executes the next hop statement in the transaction directly. That is, the error of execution is not rolled back, and the official argument is that this helps keep redis simple and efficient.
Jedis Code Demo
Multi implementation Transaction private void Dowithmulti (Jedis jedis) {Transaction Transaction = Jedis.multi ();
TRANSACTION.INCR ("Num.trans");
Transaction.set ("Val.trans", "Intrans");
Transaction.sismember ("Wilson.friends", "Tom");
System.out.println ("Transaction Result:" +transaction.exec ());
Jedis.del (New string[]{"Num.trans", "Val.trans"});
}//Optimistic lock implementation atomic operation private void Dowithmultiandcas (Jedis jedis) {list<object> res = null;
do {jedis.watch ("wilson.friends");
Boolean isfriend=jedis.sismember ("Wilson.friends", "Katty");
if (!isfriend) {Transaction Transaction = Jedis.multi ();
Various business logic TRANSACTION.INCR ("Num.trans");
Transaction.set ("Val.trans", "Intrans");
res = Transaction.exec ();
System.out.println ("Transaction result:" +res);
} while (null = = res); //Pipeline+multi Implementation Transaction private void Dowithpipeline (Jedis Jedis) {pipelineline = jedis.pipelined ();
Line.multi ();
LINE.INCR ("Num.trans");
Line.set ("Val.trans", "Intrans");
Line.sadd ("Wilson.friends", "Gary");
response<string> numres = Line.get ("Num.trans");
Line.exec ();
Line.sync ();
System.out.println ("Num.trans val:" +numres.get ()); }