"Redis caching mechanism" Detailed Java connection Redis_jedis_ transaction _java

Source: Internet
Author: User
Tags redis

Jedis Affairs

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

Transaction objects are used to manage and perform actions on various database operations. It enables and closes the database connection, executes the SQL statement, and rolls back the wrong operation.

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

Jedis the 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 
     
    //The Operation 
    transaction.set ("K4", "V4") to be executed in the transaction object; 
    Transaction.set ("K5", "V5"); 
     
    Transaction.exec ();//Execute 
  } 
} 

   

Let's check the Redis:

Found that the data has been added in

We change K4 value and K5 value to "v44" and "V55" and then add the transaction.exec () statement after the Transaction.discard () 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 
     
    //The Operation 
    transaction.set ("K4", "v44") to be executed in the transaction object; 
    Transaction.set ("K5", "V55"); 
 
    Transaction.discard ();//Rollback 
  } 
} 

   

The data insert operation is found to be rolled back and the values in the Redis have not been changed:

We simulate a transaction that brushes a credit card and use Redis 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 Te 
    Sttransaction (); 
    Boolean retvalue = T.transmethod (100); if (RetValue) {System.out.println ("Use credit card consumption success!") 
    "); }else{System.out.println ("Use credit card consumption failed!") 
    "); 
   }/** * Popular point, the Watch command is to mark a key, if a key is marked, * If the key has been modified before committing a transaction, the transaction will fail, which can usually be done in the program * try again. 
   * * First mark the balance, then check the balance is sufficient, not enough to unmark, do not make deductions; * If sufficient, start the transaction to update the operation. 
   * If the key balance is modified by someone else during this period, the error will be made when committing the transaction (exec), and it is usually possible to catch such errors in the program and execute them again until successful. 
     
    * */private Boolean transmethod (int amount) {System.out.println ("You use credit card advance" +amount+ "Yuan"); 
     
    Jedis Jedis = new Jedis ("192.168.248.129", 6379); int balance = 1000;//Available Balance int debt;//due int amttosubtract = amount;//Real Brush amount Jedis.set ("Balance", String . valueof (balance));
    Jedis.watch ("balance"); 
    Jedis.set ("Balance", "1100");/This sentence should not appear, in order to simulate the other program has modified the entry balance = Integer.parseint (Jedis.get ("balance")); 
      if (Balance < amttosubtract) {//Available balance is less than the actual brush amount, refusing to trade jedis.unwatch (); System.out.println ("Available Balance is insufficient!") 
      "); 
    return false; 
      }else{//the available balance of time to perform the deduction operation SYSTEM.OUT.PRINTLN ("Deduction fee transaction transaction start execution ..."); 
      Transaction Transaction = Jedis.multi (); Transaction.decrby ("balance", amttosubtract);//Balance minus amttosubtract amount Transaction.incrby ("debt", amttosubtract); 
      Credit card Arrears increase amttosubtract amount of money transaction.exec ()//execution Transaction balance = Integer.parseint (Jedis.get ("balance")); 
      Debt = Integer.parseint (Jedis.get ("debt")); 
       
      SYSTEM.OUT.PRINTLN ("Deduction Fee transaction transaction execution end ..."); 
      System.out.println ("Your Available Balance:" +balance); 
      System.out.println ("Your current arrears:" +DEBT); 
    return true; 
 } 
  } 
   
}

This code is to simulate the user to use a credit card brush 100 yuan of things, at this time should be deducted from the available balance of credit card 100 yuan, an increase of 100 yuan in arrears.

Run Result:

Results of Redis:

To prove that our operation was successful.

The Watch command is designed to prevent other operations from interrupting the transaction during the execution of the transaction, or to affect the calculation of the transaction, resulting in unusual occurrences such as "phantom reading" and "dirty data". The watch command creates a key, and once it is discovered that the key has been modified by someone else, the transaction will fail, and the program can usually catch such errors and then perform them again until successful. Therefore, the Watch command can ensure the synchronization of data security.

To prove the use of the Watch command, we release the Jedis.set ("balance", "1100") in the above code, and then the Transmethod method throws the interrupt exception: throws Interruptedexception, The Main method captures the interrupt exception and then pops up the corresponding warning box.

Package Cn.com.redis; 
 
Import java.util.List; 
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 Te 
    Sttransaction (); 
    Boolean retvalue=false; 
     
    Boolean interrupted = false; 
    try {retvalue = T.transmethod (100); 
      catch (Interruptedexception e) {interrupted = true; 
    System.out.println ("Transaction interrupted, please execute again!"); }finally{if (retvalue) {System.out.println ("Use credit card consumption success!") 
      "); }else{if (! Interrupted) {System.out.println ("Use credit card consumption failed!") The balance is insufficient! 
        "); /** * Popular Point, the Watch command is to mark a key, if a key is marked, * If the key has been modified before committing the transaction, the transaction will fail, which can usually be done in the program * to try Again 
   Try it once. 
   * * First mark the balance, then check the balance is sufficient, not enough to unmark, do not make deductions; * If sufficient, start the transaction to update the operation. 
   * If the key balance is modified by someone else during this period, the error will be made when committing the transaction (exec), and it is usually possible to catch such errors in the program and execute them again until successful. * */Private Boolean Transmethod (iNT amount) throws interruptedexception{System.out.println ("You use credit card advance" +amount+ "Yuan"); 
     
    Jedis Jedis = new Jedis ("192.168.248.129", 6379); int balance = 1000;//Available Balance int debt;//due int amttosubtract = amount;//Real Brush amount Jedis.set ("Balance", String 
    . valueof (balance)); 
    Jedis.watch ("balance"); 
    Jedis.set ("Balance", "1100");/This sentence should not appear, in order to simulate the other program has modified the entry balance = Integer.parseint (Jedis.get ("balance")); 
      if (Balance < amttosubtract) {//Available balance is less than the actual brush amount, refusing to trade jedis.unwatch (); System.out.println ("Available Balance is insufficient!") 
      "); 
    return false; 
      }else{//the available balance of time to perform the deduction operation SYSTEM.OUT.PRINTLN ("Deduction fee transaction transaction start execution ..."); 
      Transaction Transaction = Jedis.multi (); Transaction.decrby ("balance", amttosubtract);//Balance minus amttosubtract amount Transaction.incrby ("debt", amttosubtract); Credit card arrears increase amttosubtract of money list<object> result = transaction.exec ()//Execution transaction if (result==null) {//Transaction 
         
   Failure to submit, indicating that data has been modified during execution     SYSTEM.OUT.PRINTLN ("Deduction fee transaction transaction execution interrupted ..."); 
         
      throw new Interruptedexception (); 
        }else{//Transaction submitted successfully balance = Integer.parseint (Jedis.get ("balance")); 
        Debt = Integer.parseint (Jedis.get ("debt")); 
         
        SYSTEM.OUT.PRINTLN ("Deduction Fee 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 the transaction is committed, the execution of the transaction will not succeed, which guarantees the security of the data.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.