0
点赞
收藏
分享

微信扫一扫

记录在项目中乐观锁的简单使用

三次方 2021-09-24 阅读 18
日记本

记录在项目中乐观锁的简单使用

我们工作用的是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)就可

举报

相关推荐

0 条评论