[redis caching mechanism] detailed explanation of Java connection to redis_ Jedis_ affair

Jedis transaction

When we use JDBC to connect to MySQL, we need to start the transaction every time before executing the SQL statement; In mybatis, you also need to use opensession () to obtain the session transaction object for SQL execution, query and other operations. When our operation on the database ends, the transaction object is responsible for closing the database connection.

Transaction objects are used to manage and execute various database operations. It can open and close database connections, execute SQL statements, and roll back wrong operations.

Our redis also has transaction management objects, which are located in redis clients. jedis. Transaction.

Jedis transaction related code:

Let's take a look at redis:

Found that the data has been added

We change the value of K4 and K5 to "v44" and "V55", and then in transaction After the exec () statement, add transaction Discard() statement:

You will find that the data insertion operation is rolled back, and the two values in redis have not been changed:

We simulate a credit card transaction and use redis transaction to process some logic:

This code simulates that the user swiped 100 yuan with a credit card. At this time, the available balance of the credit card should be reduced by 100 yuan and the debt of 100 yuan should be increased.

Operation results:

Redis results:

It proves that our operation is successful.

The purpose of adding the watch command is to prevent other operations from interrupting the transaction or affecting the calculation results of the transaction, resulting in abnormal conditions such as "unreal reading" and "dirty data". The watch command establishes a key. Once it is found that the key has been modified during execution, the transaction will fail. This kind of error can usually be caught in the program and executed again until it succeeds. Therefore, the watch command can ensure the safety of data synchronization.

In order to prove the purpose of the watch command, we put jedis in the above code set("balance","1100"); The annotation is released, and then the transmethod method throws an interrupt exception: throws interruptedexception. The main method catches the interrupt exception, and then pops up the corresponding warning box.

Run again to see the effect:

This shows that if the data is modified after the watch command is executed and before the transaction is committed, the transaction execution will not succeed, which ensures the security of the data.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>