preface
- 1. Multiple processes and threads access the common component database
- 2. Through the select… For UPDATE accesses the same data
- 3. Use for update to lock other data so that other threads have to wait
Database section
-
1. Create a table with the following fields.
Code section
- 1.DistributeLockMapper.xml
<select id="selectDistributeLock" resultType="com.example.distributelock.model.DistributeLock">
select * from distribute_lock
where business_code = #{businessCode,jdbcType=VARCHAR}
for update
</select>
Copy the code
- 2.DistributeLock.java
public class DistributeLock { private Integer id; private String businessCode; private String businessName; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getBusinessCode() { return businessCode; } public void setBusinessCode(String businessCode) { this.businessCode = businessCode == null ? null : businessCode.trim(); } public String getBusinessName() { return businessName; } public void setBusinessName(String businessName) { this.businessName = businessName == null ? null : businessName.trim(); }}Copy the code
- 3.DistributeLockMapper.java
public interface DistributeLockMapper { DistributeLock selectDistributeLock(@Param("businessCode") String businessCode); }Copy the code
- 4.TestController.java
@RestController public class TestController { @Resource private DistributeLockMapper distributeLockMapper; @RequestMapping("singleLock") @Transactional(rollbackFor = Exception.class) public String singleLock() throws Exception { DistributeLock distributeLock = distributeLockMapper.selectDistributeLock("test"); If (distributeLock==null) throw new Exception(" distributeLock not found "); try { Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); } return "I'm done!" ; }}Copy the code