秒杀模块碎碎念笔记(2)-Service层

来源:互联网 发布:动漫 神作 知乎 编辑:程序博客网 时间:2024/05/21 06:13

dto:web与service层之间传输用
一般需要不同变量的构造方法来返回不同状态的结果


定义错误类:

public class SeckillException extends RuntimeException {    public SeckillException(String message) {        super(message);    }    public SeckillException(String message, Throwable cause) {        super(message, cause);    }}

通常定义一个总的错误类型,然后其他子错误继承它,并为具体service接口定义抛出的异常
在service整体补抓异常,除了我们自己定义的异常外,dao层还可能出现数据库断开连接/数据库超时等异常
编译时异常整体抛出时,先要捕捉子类异常


打印错误日志

private Logger logger= LoggerFactory.getLogger(this.getClass());logger.error(e.getMessage(),e);

枚举的使用:

public enum SeckillStatEnum {    SUCCESS(1,"秒杀成功"),    END(0,"秒杀结束"),    REPEAT_KILL(-1,"重复秒杀"),    INNER_ERROR(-2,"系统异常"),    DATE_REWRITE(-3,"数据篡改");    private int state;    private String info;    SeckillStatEnum(int state, String info) {        this.state = state;        this.info = info;    }    public int getState() {        return state;    }    public String getInfo() {        return info;    }    public static SeckillStatEnum stateOf(int index)    {        for (SeckillStatEnum state : values())        {            if (state.getState()==index)            {                return state;            }        }        return null;    }}
public SeckillExecution(long seckillId, SeckillStatEnum statEnum, SuccessKilled successKilled) {    this.seckillId = seckillId;    this.state = statEnum.getState();    this.stateInfo = statEnum.getInfo();    this.successKilled = successKilled;}

spring-service 放所有service有关,自动包括子包


事务只有在抛出运行时异常才回滚,不要乱用trycatch,因为如果有异常的话还是会被提交
尽可能保证执行时间短:不要穿插网络请求,也就是不要在事务方法里面写运行时间长的事务
如果需要长时间的方法:需要剥离,写到上层就可以
不是所有的方法都需要事务:只有一条修改操作/只读操作
需要了解行级锁的内容


idea xml 中在一个配置文件中引入另外一个文件的bean可能会出错,但是运行其实是没错的