Imooc·Java高并发秒杀API(枚举与异常处理)

Imooc·Java高并发秒杀API(枚举与异常处理)

一、项目中一共用到一个枚举(SeckillStatEnum)

public enum SeckillStatEnum {
	
	SUCCESS(1,"秒杀成功"), 
	END(0,"秒杀结束"),
	REPEAT_KILL(-1,"重复秒杀"),
	INNER_ERROR(-2,"系统异常"),
	DATE_REWRITE(-3,"数据篡改");
	
	private int state;
	
	private String stateInfo;

	SeckillStatEnum(int state, String stateInfo) {
		this.state = state;
		this.stateInfo = stateInfo;
	}

	public int getState() {
		return state;
	}

	public String getStateInfo() {
		return stateInfo;
	}
	
	public static SeckillStatEnum statOf(int index){
		for(SeckillStatEnum state : values())
			if(state.getState() == index) 
				return state;
			return null;
	}
	
}

二、和三个自定义异常(RepeatKillException、SeckillCloseException、SeckillException)并在ServiceImpl中将编译器异常转换为运行期异常

public SeckillExecution executeSeckill(long seckillId, long userPhone,
			String md5) throws SeckillException, SeckillCloseException,
			RepeatKillException {
		if(md5 == null || !md5.equals(getMD5(seckillId)))
			throw new SeckillException("seckill date rewrite");
		Date nowTime = new Date();
		int updateCount = seckillDao.reduceNumber(seckillId, nowTime);
		try {
			if(updateCount <= 0) throw new SeckillCloseException("seckill is close");
			else {
				int insertCount = successKilledDao.insertSuccessKilled(seckillId, userPhone);
				if(insertCount <= 0) throw new RepeatKillException("seckill repeated");
				else {
					SuccessKilled successKilled = successKilledDao.queryByIdWithSeckill(seckillId, userPhone);
					//return new SeckillExecution(seckillId, 1, "秒杀成功", successKilled);
					return new SeckillExecution(seckillId, SeckillStatEnum.SUCCESS, successKilled);
				}
			}
		} catch (SeckillCloseException e1) {
			throw e1;
		} catch (RepeatKillException e2) {
			throw e2;
		} catch (Exception e) {
			//e.printStackTrace();
			logger.error(e.getMessage());
			//将所有编译器异常转换为运行期异常
			throw new SeckillException("seckill inner error :" + e.getMessage());
		}
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值