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

来源:互联网 发布:delphi 车牌识别算法 编辑:程序博客网 时间:2024/05/21 23:00

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 0
原创粉丝点击