BIGE_BIGGER
BIGE_BIGGER
采纳率10%
2019-04-25 18:09 阅读 2.1k

mysql 悲观锁 for update 无效问题

20

问题:springboot 项目,对数据库加行锁,多线程测试结果仍然是不安全的。

实体类:和数据库表对应,数据库表主键id建立了索引

@Entity
@Table(name = TableName.TABLE_SPORTRECORDID)
@JsonInclude(value= JsonInclude.Include.NON_EMPTY)
public class SportRecordId {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;

    //跑步记录的唯一Id
    private Integer useageid;
        //省去setter .getter
        }

Repository

@Repository
public interface SportRecordIdRepository extends PagingAndSortingRepository<SportRecordId, Integer> {

    @Query(nativeQuery=true,value = "select a.* from sportrecordid a where a.id = ?1 for update")
    Optional<SportRecordId> findSportRecordIdForUpdate(Integer id);
}

Service

     @Autowired
    private SportRecordIdRepository sportRecordIdRepository;

    @Override
    //@Transactional(isolation = Isolation.SERIALIZABLE)
    public Integer getSportRecordIdForUpdate(Integer id) {
        SportRecordId res  = sportRecordIdRepository.findSportRecordIdForUpdate(id).orElse(null);
        if(res!=null)
        {
            res.setUseageid(res.getUseageid()+1);
            SportRecordId saved = sportRecordIdRepository.save(res);
            return saved.getUseageid();
        }
        else
        {
            throw new ServiceException(ServiceErrorCode.SERVER_BUSY.getCode(),ServiceErrorCode.SERVER_BUSY.getMessage());
        }
    }

多线程测试
图片说明

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

相关推荐