preface
In business design, anti-redo design is a key point. Taking interface design as an example, anti-redo is to prevent the interface from being called many times and producing dirty data, such as repeated payment of payment orders. Therefore, anti-redo is very important.
When multiple calls occur
There are subjective reasons for the occurrence of multiple call interfaces, such as repeated request attacks and user misoperations. There are also objective reasons, such as timeout retries for robustness;
- Repeat request attack
For this malicious attack, actually belongs to the security category, we can deal with it through blacklist + traffic limiting, and then consider anti-reprocessing;
- User misoperations
For example, when a user clicks the submit button on the interface, the user clicks the submit button several times due to hand error. In this case, the client can do some processing to reduce the user’s misoperation, such as the button turning gray after submission. Of course, the prevention of reprocessing by the supplier is also essential;
- Timeout retry
In order to ensure the robustness of the system, the interface caller often does some retry processing. For example, various RPC frameworks have built fault tolerance mechanisms for us, so the provider needs to prevent retries.
In fact, the core of how to prevent reprocessing is to ensure that multiple identical requests are executed only once, or that the effect of multiple calls is the same as that of one call, which is to ensure idempotency as we often say.
When you need weight protection
All operations in the final analysis are to add, delete, change and check, in fact, we really need to do anti-reprocessing, more important is to increase and modify; Query and delete themselves execute once and many times, produce the same effect, there is natural idempotent, although said to have natural idempotent, but the query and delete itself is also to consume resources, if can prevent repeated execution, can also save resources; The increase and modification must be anti-weight. The increase can be taken as an example, and the modification can be taken as an example to update the inventory. If the anti-weight is not done well, the consequences will be very serious. Take a look at the following specific measures to prevent heavy;
How to prevent heavy
The above mentioned is mainly for the increase and modification of the need to do a good job of anti-gravity treatment, of course, for the increase and modification is actually different anti-gravity measures, there are unified ways, respectively introduced below;
Unified the heavy
- Token mechanism
The server needs to provide the service of obtaining the token mechanism, so that the client obtains the token each time it requests, and the server saves the token in Redis. When the client sends a request, it will bring the token with it, so that the server can get the token and delete it directly in Redis, and judge whether it is successful according to the return value:
localhost:0>get token
"111"
localhost:0>del token
"1"
localhost:0>del token
"0"
Copy the code
Store tokens in Redis, which works well in a distributed environment.
- The heavy key
The MD5 ciphertext is generated according to the request parameters and stored in redis as the key. You can run the setnx command to ensure that only one ciphertext can be saved successfully.
key = MD5.md5("param1="+param1+"¶m2="+param2...)
localhost:0>setnx key 1
"1"
localhost:0>setnx key 1
"0"
Copy the code
- The heavy table
You can make use of the unique index constraint of the table. You can use similar anti-replay key as the unique index field. Only one anti-replay key is inserted successfully after multiple requests.
In fact, the above methods are not related to the specific business, and can be applied to most scenarios; And through Redis or database, as well as atomic operation to ensure that the distributed environment can also run well;
Insert the heavy
- select+insert
The first thought of data insertion is to check whether the data is inserted first, and then insert, but there are obviously two operations, not atomic operation, single node can also be solved by locking, distributed environment needs to use distributed lock to ensure atomicity; It can also be used in combination with other methods, such as the unique primary key mechanism below;
- Only the primary key
In this way, we do not directly use the auto-increment primary key of the database, and use the distributed ID algorithm to generate, so that when inserting data can be constrained by the unique primary key, to ensure that only one will succeed;
- Rollback mechanism
Some businesses actually have forward and reverse processes, such as payment order, judge the status of the order when receiving the successful payment notice from the bank. If the payment has been successful, you can directly go through the refund process.
Update the heavy
- Optimistic locking
Optimistic locking is often used in update scenarios, such as the following by way of version numbers:
update table_name
sale = sale + 1,
version = version + 1,
WHERE id = #{id}
AND version = #{version}
Copy the code
- State machine optimistic locking
In the business of related orders, many will involve the state machine. The state is in circulation, and only after the previous state can there be the next state. For example, common shopping orders include: unpaid submission, successful payment, waiting for delivery, delivery in progress, signed for receipt, etc., each state needs the pre-state;
Update table_name set status = next status where id = #{id} and status = #{status}Copy the code
conclusion
There are many ways to prevent weight loss. We often need to make relevant choices for our own business. Different businesses, different business volumes and different tolerance levels will affect how we do anti-weight loss. Each approach is not independent, and sometimes multiple approaches need to be integrated.
Thank you for attention
You can pay attention to the wechat public account “Roll back the code”, read the first time, the article continues to update; Focus on Java source code, architecture, algorithms, and interviews.