记录在项目中乐观锁的简单使用
前言:项目中有一个商品表,当购买商品表的时候份额会减一,当有多个购买请求时,可能会出现超卖现象,所以为了避免这个问题,我们就简单的用来乐观锁(毕竟是个小项目)
我们工作用的是spring data jpa ,所以就是在实体类中使用加上一个@Version注解
实体类 MallProduct
@Data
@Entity
@DynamicUpdate
@Accessors(chain = true)
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@Table(indexes = {@Index(columnList = "productName")})
public class MallProduct extends BaseMySqlModel {
//别的字段就不放上来了,毕竟是公司的机密
@Version
private Integer version;
}
BaseMySqlModel是因为阿里规约说,每个表必须要有id,gmt_create,gmt_modified,所以我们就弄了一个这个类,所以表的实体类都继承他就好了
BaseMySqlModel
@Data
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseMySqlModel implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@JsonIgnore
@CreatedDate
private Date gmtCreate;
@JsonIgnore
@LastModifiedDate
private Date gmtModified;
}
OrderServiceImpl
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
//这是我们定义在常量类里的
public final static int OPTIMISTIC_LOCK_MAX_TRY = 10;
@Transactional(rollbackFor = Exception.class)
public synchronized OrderVO createOrder(MallCreateOrderBO mallCreateOrderbo ) {
int count = 0;
while (count++ < OPTIMISTIC_LOCK_MAX_TRY) {
//业务处理
try {
//创建订单操作
} catch (ObjectOptimisticLockingFailureException e) {
log.warn("OptimisticLockingFailure:createOrder");
continue;
}
break;
}
if (count > OPTIMISTIC_LOCK_MAX_TRY) {
throw new Exception("Create order failed", "下单失败");
}
}
很简单的乐观锁应用,下单操作执行10遍,毕竟阿里规约上说乐观锁重试不能小于三次
如果要使用悲观锁的话,在你DAO,方法上增加@Lock(LockModeType.PESSIMISTIC_WRITE)
就可
都看到这里了,觉得还可以的话,点个赞吧,喜欢那种红色通知的感觉