"Redis cache mechanism" 13.Java Connection Redis_jedis_ Transaction

Source: Internet
Author: User

Jedis transactions
When we use JDBC to connect to MySQL, we need to open the transaction every time we execute the SQL statement; in MyBatis,
You also need to use opensession () to get the session transaction object for SQL execution, query, and so on. When we
At the end of the operation on the database, the transaction object is responsible for shutting down the database connection.

Transaction objects are used to manage and perform actions for various database operations. It can turn database connections on and off, execute SQL
Statement to roll back the wrong operation.

Our Redis also has a transaction management object, which is located under Redis.clients.jedis.Transaction.

Jedis related code for the transaction:
Package Cn.com.redis;import Redis.clients.jedis.jedis;import Redis.clients.jedis.transaction;public class Test7 { Public    static void Main (string[] args) {        Jedis Jedis = new Jedis ("192.168.248.129", 6379);                Transaction Transaction=jedis.multi ();//Returns a transaction control object                //pre-loaded in the transaction object to perform the Operation        transaction.set ("K4", "V4");        Transaction.set ("K5", "V5");                Transaction.exec ();//Execute    }}
Let's look at Redis:

Discovery data has been added.

We changed the value of K4 and K5 to "v44" and "V55",
Then add the Transaction.discard () statement after the transaction.exec () statement:
Package Cn.com.redis;import Redis.clients.jedis.jedis;import Redis.clients.jedis.transaction;public class Test7 { Public    static void Main (string[] args) {        Jedis Jedis = new Jedis ("192.168.248.129", 6379);                Transaction Transaction=jedis.multi ();//Returns a transaction control object                //pre-loaded in the transaction object to perform the Operation        transaction.set ("K4", "v44");        Transaction.set ("K5", "V55");        Transaction.discard ();//Rollback    }}
It is found that the data insert operation was rolled back and that the two values in Redis were not changed:


We simulate a transaction that brushes a credit card, and uses Redis's transactions to handle some logic:
Package Cn.com.redis;import Redis.clients.jedis.jedis;import Redis.clients.jedis.transaction;public class testtransaction {//analog credit card consumption and repayment public static void main (string[] args) {testtransaction t = new Testtransacti        On ();        Boolean retvalue = T.transmethod (100); if (RetValue) {System.out.println ("Use credit card to spend success!        "); }else{System.out.println ("Using credit card consumption failed!")        ");     }}/** * Popular point, the Watch command is to mark a key, if a key is marked, * before committing a transaction if the key was modified by someone else, the transaction will fail, which can usually be in the program * re-try again.     * * First mark the balance, then check whether the balance is sufficient, not enough to cancel the mark, do not deduct; * If sufficient, start the transaction for the update operation.     * If the key balance is modified by someone else during this period, it will be an error when committing the transaction (EXEC), * The program can usually catch such errors and re-execute them again until successful.                * */private Boolean transmethod (int amount) {System.out.println ("You use credit card prepayment" +amount+ "Yuan");                Jedis Jedis = new Jedis ("192.168.248.129", 6379); int balance = 1000;//Available Balance int debt;//amount owed int amttosubtract = amount;//actual brush limit jedis.set ("balance" , String.valueof (balance));        Jedis.watch ("balance");        Jedis.set ("Balance", "1100");//This sentence should not appear, in order to simulate other programs have modified the entry balance = Integer.parseint (Jedis.get ("balance"));            if (Balance < amttosubtract) {//The available balance is less than the actual brush amount, reject the transaction jedis.unwatch (); SYSTEM.OUT.PRINTLN ("Insufficient Available Balance!")            ");        return false;            }else{//when the available balance is sufficient to carry out the deduction operation System.out.println ("The deduction transaction the transaction begins to execute ...");            Transaction Transaction = Jedis.multi (); Transaction.decrby ("balance", amttosubtract);//Balance minus amttosubtract money Transaction.incrby ("debt", amttosubtract);//            Credit card arrears Increase amttosubtract money transaction.exec ();//execute Transaction balance = Integer.parseint (Jedis.get ("balance"));            Debt = Integer.parseint (Jedis.get ("debt"));                        SYSTEM.OUT.PRINTLN ("Deduction transaction transaction Execution end ...");            System.out.println ("Your Available Balance:" +balance);            System.out.println ("Your current arrears:" +DEBT);        return true; }    }    }

This code is to impersonate the user to use the credit card to brush 100 yuan thing, this time should subtract the credit card's available Balance 100 yuan,
An increase of $100 in arrears.

Operation Result:


Results of Redis:

Prove that our operation was successful.

The Watch command is designed to prevent other operations from interrupting a transaction during the execution of a transaction, or to affect the result of a transaction's calculation.
Cause "phantom read", "dirty data" and other abnormal conditions occur. The watch command establishes a key that, once found in the execution process,
If the key is modified by someone else, the transaction will fail, and the program can usually catch such errors and execute them again until it succeeds.
So the watch command can keep the data synchronized and secure.

To prove the purpose of the watch command, we put the Jedis.set ("balance", "1100") in the above code, and the comment is released,
The Transmethod method then throws a break exception: The throws Interruptedexception,main method captures the interrupt exception,
Then the appropriate warning box pops up.
Package Cn.com.redis;import Java.util.list;import Redis.clients.jedis.jedis;import redis.clients.jedis.Transaction  ;p Ublic class Testtransaction {//analog credit card consumption and repayment public static void main (string[] args) {testtransaction t = new        Testtransaction ();        Boolean retvalue=false;                Boolean interrupted = false;        try {retvalue = T.transmethod (100);            } catch (Interruptedexception e) {interrupted = true;        SYSTEM.OUT.PRINTLN ("The transaction is interrupted, please re-execute!"); }finally{if (retvalue) {System.out.println ("Use credit card to spend success!            "); }else{if (! Interrupted) {System.out.println ("failed with credit card consumption! Insufficient balance!                "); }}}}/** * Popular point, the Watch command is to mark a key, if a key is marked, * before committing a transaction if the key was modified by someone else, the transaction will fail, which can usually be in the program *     Try again.     * * First mark the balance, then check whether the balance is sufficient, not enough to cancel the mark, do not deduct; * If sufficient, start the transaction for the update operation. * If the key balance is modified by someone else during this period, it will be an error when committing the transaction (EXEC), * The program can usually catch such errors and then re-execute aTimes until it succeeds. * */private Boolean transmethod (int amount) throws interruptedexception{System.out.println ("You use credit card prepayment"                +amount+ "Yuan");                Jedis Jedis = new Jedis ("192.168.248.129", 6379); int balance = 1000;//Available Balance int debt;//amount owed int amttosubtract = amount;//actual brush limit jedis.set ("balance"        , string.valueof (balance));        Jedis.watch ("balance");        Jedis.set ("Balance", "1100");//This sentence should not appear, in order to simulate other programs have modified the entry balance = Integer.parseint (Jedis.get ("balance"));            if (Balance < amttosubtract) {//The available balance is less than the actual brush amount, reject the transaction jedis.unwatch (); SYSTEM.OUT.PRINTLN ("Insufficient Available Balance!")            ");        return false;            }else{//when the available balance is sufficient to carry out the deduction operation System.out.println ("The deduction transaction the transaction begins to execute ...");            Transaction Transaction = Jedis.multi (); Transaction.decrby ("balance", amttosubtract);//Balance minus amttosubtract money Transaction.incrby ("debt", amttosubtract);// Credit card arrears increase amttosubtract of money List<object> result = Transaction.exec ();//Execute transaction if (result==null) {//Transaction commit failed, indicating that data was modified during execution                SYSTEM.OUT.PRINTLN ("Deduction transaction transaction execution interruption ...");                            throw new Interruptedexception ();                }else{//Transaction submitted successfully balance = Integer.parseint (Jedis.get ("balance"));                Debt = Integer.parseint (Jedis.get ("debt"));                                SYSTEM.OUT.PRINTLN ("Deduction transaction transaction Execution end ...");                System.out.println ("Your Available Balance:" +balance);                                System.out.println ("Your current arrears:" +DEBT);            return true; }        }    }    }
Run it again and look at the effect:


This means that if the data has been modified before the watch command executes and before the transaction commits, the transaction execution will not succeed.

This ensures the security of the data.

Reprint Please specify source: http://blog.csdn.net/acmman/article/details/53579378

"Redis cache mechanism" 13.Java Connection Redis_jedis_ Transaction

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.