ssm实现秒杀总结 适合新手 二
上一篇我们实现了DAO层
接下来实现service层
先配置一下spring
这里我写的是spring-service.xml
ref ="dataSource"可能会飘红,但是不用担心,这是因为dataSource不在这个xml文件里,而是在spring-dao.xml里面,加载的时候能加载到
这里使用基于注解的声明式事务,因为实际上我们只有一个方法能用到事务
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--扫描service包下所有使用注解的类型-->
<context:component-scan base-package="com.zmf.service"></context:component-scan>
<!--配置事务管理器-->
<bean id ="transactionManage" class ="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据库连接池-->
<property name="dataSource" ref ="dataSource"></property>
</bean>
<!--配置基于注解的声明式事务,默认使用注解来管理声明式事务-->
<tx:annotation-driven transaction-manager="transactionManage"></tx:annotation-driven>
</beans>
接下来看一下service:
/**
* 站在使用者的角度设计方法
* 三个方面: 方法定义力度,参数,返回类型
*/
public interface SeckillService {
//查询所有秒杀记录
List<Seckill> getSeckillList();
//查询单个秒杀记录
Seckill getById(long seckillId);
//秒杀开启 输出秒杀接口地址
//否则输出系统时间和秒杀时间
Exposer exportSeckillUrl(long seckillId);
//执行秒杀操作
SeckillExcution excuteSeckill(long seckillId, long userPhone, String md5)
throws SeckillException,RepeatKillException,SeckillCloseException;
}
Exposer 和SeckillExcution 是我们定义的类,用于存储方法返回信息
public class Exposer {
//是否开启秒杀
private boolean exposed;
//加密措施
private String md5;
//秒杀id
private long seckillId;
//系统当前时间
private long now;
//秒杀开始时间
private long start;
//秒杀结束时间
private long end;
public Exposer(boolean exposed, long seckillId, long now, long start, long end) {
this.exposed = exposed;
this.seckillId=seckillId;
this.now = now;
this.start = start;
this.end = end;
}
public Exposer(boolean exposed, String md5, long seckillId) {
this.exposed = exposed;
this.md5 = md5;
this.seckillId = seckillId;
}
public Exposer(boolean exposed, long seckillId) {
this.exposed = exposed;
this.seckillId = seckillId;
}
//封装秒杀执行后的结果
public class SeckillExcution {
//秒杀id
private long seckillId;
//秒杀标志位
private int state;
//标志位的具体信息
private String stateInfo;
//秒杀记录
private SuccessKilled successKilled;
//创建了一个枚举类SeckillStatEnum封装了 state 和stateinfo
public SeckillExcution(long seckillId, SeckillStatEnum statEnum, SuccessKilled successKilled) {
this.seckillId = seckillId;
this.state = statEnum.getState();
this.stateInfo = statEnum.getStateInfo();
this.successKilled = successKilled;
}
//若秒杀失败,则只传id和状态信息
public SeckillExcution(long seckillId, SeckillStatEnum statEnum) {
this.seckillId = seckillId;
this.state = statEnum.getState();
this.stateInfo = statEnum.getStateInfo();
}
public enum SeckillStatEnum {
SUCCESS(1,"秒杀成功"),
END(0,"秒杀结束"),
REPEAT_KILL(-1,"重复秒杀"),
INNER_ERROR(-2,"系统异常"),
DATA_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 stateOf(int index){
for(SeckillStatEnum state:values()){
if(state.getState() == index){
return state;
}
}
return null;
}
}
//为了篇幅省略了set,get和tostring方法
然后我们来看一下service的实现类,只有excuteSeckill方法用到了事务
@Service
public class SeckillServiceImpl implements SeckillService {
private Logger logger = LoggerFactory.getLogger(this.getClass());
//自动注入注入ioc容器里的bean
@Autowired
private SeckillDao seckillDao;
@Autowired
private SuccessKilledDao successKilledDao;
private final String slat="fbjksfh";
@Override
public List<Seckill> getSeckillList() {
return seckillDao.queryAll(0,4);
}
@Override
public Seckill getById(long seckillId) {
return seckillDao.queryById(seckillId);
}
@Override
public Exposer exportSeckillUrl(long seckillId) {
Seckill seckill = seckillDao.queryById(seckillId);
if(seckill==null){
return new Exposer(false,seckillId);
}
Date startTime = seckill.getStartTime();
Date endTime = seckill.getEndTime();
//系统当前时间
Date nowTime = new Date();
if(nowTime.getTime()<startTime.getTime()
||nowTime.getTime()>endTime.getTime()){
return new Exposer(false,seckillId,nowTime.getTime(),
startTime.getTime(),endTime.getTime());
}
String md5 = getMd5(seckillId);
return new Exposer(true,md5,seckillId);
}
private String getMd5(long seckillId ){
String base = seckillId+"/"+slat;
String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
return md5;
}
@Override
@Transactional
//使用注解控制事务方法的优点
/**1.开发团队达成一支约定,明确标注事务方法的编程风格
* 2.保证事务方法的执行时间尽可能短,不要穿插其他的网络操作,RPC/HTTP请求
* 3.不是所有的方法都需要事务
*/
public SeckillExcution excuteSeckill(long seckillId, long userPhone, String md5)
throws SeckillException, RepeatKillException, SeckillCloseException {
if(md5==null || (!md5.equals(getMd5(seckillId)))){
throw new SeckillException("seckill data rewrite");
}
//执行秒杀逻辑
Date nowTime = new Date();
try{
//减库存
int updateCount = seckillDao.reduceNumber(seckillId,nowTime);
if(updateCount <=0){
//没有更新到记录,秒杀结束
throw new SeckillCloseException("seckill is closed");
}else{
//记录购买行为
int insertCount = successKilledDao.insertSuccessKilled(seckillId,userPhone);
if(insertCount <=0){
//重复秒杀
throw new RepeatKillException("seckill repeat");
}else {
//秒杀成功
SuccessKilled successKilled = successKilledDao.queryByIdWithSeckill(seckillId, userPhone);
return new SeckillExcution(seckillId, SeckillStatEnum.SUCCESS, successKilled);
}
}
}catch (SeckillCloseException e1){
throw e1;
}catch(RepeatKillException e2){
throw e2;
}catch (Exception e){
logger.error(e.getMessage(),e);
//所有编译期异常,转化为运行期异常
throw new SeckillException("seckill inner error:"+e.getMessage());
}
}
}
定义了异常类,为了确定是那部分发生了异常
public class SeckillException extends RuntimeException {
public SeckillException(String message) {
super(message);
}
public SeckillException(String message, Throwable cause) {
super(message, cause);
}
}
//秒杀关闭异常
public class SeckillCloseException extends SeckillException{
public SeckillCloseException(String message) {
super(message);
}
public SeckillCloseException(String message, Throwable cause) {
super(message, cause);
}
}
//重复秒杀异常,运行时异常
public class RepeatKillException extends SeckillException{
public RepeatKillException(String message) {
super(message);
}
public RepeatKillException(String message, Throwable cause) {
super(message, cause);
}
}
这样service层也就完成了
附一下工程文件link