[Original] JMS achieves Distributed Transaction consistency and jms transaction consistency
The topic of distributed transactions has always been a controversial topic. Here we will give a simple demo of how to implement distributed transactions using message-oriented middleware, it also allows you to gain experience and think about distributed transactions in practice. 1. Local transaction
After configuring transaction management, the traditional java frameworks such as ssh, ssm, and ssi can ensure transaction consistency; for example, in the same database, when A transfers 100 yuan to B and sends 100 vouchers, whether the server fails or the transfer fails, an exception is thrown, in the end, A's money can be guaranteed to either be transferred out successfully. B receives 100 yuan and coupons, or neither A nor B has changed.
2. distributed transactions
The balance and coupon tables are distributed in databases on different nodes. The transfer and issuance of coupons are different applications. They use rpc, httpclient, and mq to achieve message interconnection. At this time, A successfully transfers money to B, but what should we do if coupon issuance fails?
3. Use ActiveMq to achieve transaction consistency
- The implementation process is to issue a voucher after the user registers. In this article, the user registers as an application, and the coupon is another application. messages are sent and received through activemq, that is, after the user registration is successful, the user information is pushed to the Message Middleware. In the coupon application, message monitoring is implemented to issue coupons. Therefore, this process is divided into two steps. In our daily enterprise development, distributed development extracts each business as a separate project, in this way, the normal operation of other services will not be affected after a project fails.
- First, create two maven projects, called account and voucher. Here I use springmvc + jdbc as the Project Skeleton.
- In the account, I created a UserController. java is used as the registration entry to write the registration method. The registration method is shown in figure. Note that a message table is added, which will be answered in detail below the message table.
The main use of the message table is to assume that after a message is delivered to the message-oriented middleware, the consumer crashes and a batch of coupons to be sent are accumulated. At this time, we certainly cannot ignore them, you need to take the initiative to query the table to be sent after the consumer restarts, if the status is to be sent, all are sent out.