Java实现分布式锁-基于数据库(1)

210 阅读1分钟

前言

  • 1.多个进程、多个线程访问共同的组件数据库
  • 2.通过select...for update 访问同一条数据
  • 3.通过 for update锁定其他数据,让其他线程只能等待

数据库部分

  • 1.创建一张表,字段如下;

代码部分

  • 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>
  • 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();
    }
}
  • 3.DistributeLockMapper.java
public interface DistributeLockMapper {
	DistributeLock selectDistributeLock(@Param("businessCode") String businessCode);
}
  • 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("分布式锁找不到");
      try {
          Thread.sleep(20000);
      } catch (InterruptedException e) {
          e.printStackTrace();
      }
      return "我已经执行完成!";
  }
}