源码:https://github.com/joshul/seckill
开始Service层的编码之前,我们首先需要进行Dao层编码之后的思考:在Dao层我们只完成了针对表的相关操作包括写了接口方法和映射文件中的sql语句,并没有编写逻辑的代码,例如对多个Dao层方法的拼接,当我们用户成功秒杀商品时我们需要进行商品的减库存操作(调用SeckillDao接口)和增加用户明细(调用SuccessKilledDao接口),这些逻辑我们都需要在Service层完成。这也是一些初学者容易出现的错误,他们喜欢在Dao层进行逻辑的编写,其实Dao就是数据访问的缩写,它只进行数据的访问操作,接下来我们便进行Service层代码的编写。
1. 秒杀Service接口设计
在org.seckill包下创建一个service包用于存放我们的Service接口和其实现类,创建一个exception包用于存放service层出现的异常例如重复秒杀商品异常、秒杀已关闭等异常,一个dto包作为传输层,dto和entity的区别在于:entity用于业务数据的封装,而dto用于完成web和service层的数据传递。
首先创建我们Service接口,里面的方法应该是按”使用者”(程序员)的角度去设计,SeckillService.java,代码如下:
package org.seckill.service;
import org.seckill.dto.Exposer;
import org.seckill.dto.SeckillExecution;
import org.seckill.entity.Seckill;
import org.seckill.exception.RepeatKillException;
import org.seckill.exception.SeckillCloseException;
import org.seckill.exception.SeckillException;
import java.util.List;
/**
* 业务接口:站在"使用者"角度设计接口
* 三个方面:方法定义粒度,参数,返回类型(return 类型/异常)
*/
public interface SeckillService {
/**
* 查询所有秒杀记录
* @return List<Seckill>
*/
List<Seckill> getSeckillList();
/**
* 查询单个秒杀记录
* @param seckillId
* @return Seckill
*/
Seckill getById(long seckillId);
/**
* 秒杀开启时输出秒杀接口地址,
* 否则输出系统时间个秒杀时间
* @param seckillId
* @return Exposer
*/
Exposer exportSeckillUrl(long seckillId);
/**
* 执行秒杀操作
* @param seckillId
* @param userPhone
* @param md5
* @return SeckillExecution
*/
SeckillExecution executeSeckill(long seckillId, long userPhone, String md5)
throws SeckillException,RepeatKillException,SeckillCloseException;
/**
* 存储过程执行秒杀
* @param seckillId
* @param userPhone
* @param md5
* @return
* SeckillExecution
*
*/
SeckillExecution executeSeckillProcedure(long seckillId,long userPhone,String md5);
}
该接口中前面两个方法返回的都是跟我们业务相关的对象,而后两个方法返回的对象与业务不相关,这两个对象我们用于封装service和web层传递的数据,方法的作用我们已在注释中给出。相应在的dto包中创建Exposer.java,用于封装秒杀的地址信息,各个属性的作用在代码中已给出注释,代码如下:
package org.seckill.dto;
/**
* Created by joshul on 2017/2/8.
* 暴露秒杀地址DTO
*/
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, String md5, long seckillId) {
this.exposed = exposed;
this.md5 = md5;
this.seckillId = seckillId;
}
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, long seckillId) {
this.exposed = exposed;
this.seckillId = seckillId;
}
public boolean isExposed() {
return exposed;
}
public void setExposed(boolean exposed) {
this.exposed = exposed;
}
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
public long getSeckillId() {
return seckillId;
}
public void setSeckillId(long seckillId) {
this.seckillId = seckillId;
}
public long getNow() {
return now;
}
public void setNow(long now) {
this.now = now;
}
public long getStart() {
return start;
}
public void setStart(long start) {
this.start = start;
}
public long getEnd() {
return end;
}
public void setEnd(long end) {
this.end = end;
}
@Override
public String toString() {
return "Exposer{" +
"exposed=" + exposed +
", md5='" + md5 + '\'' +
", seckillId=" + seckillId +
", now=" + now +
", start=" + start +
", end=" + end +
'}';
}
}
和SeckillExecution.java,用于判断秒杀是否成功,成功就返回秒杀成功的所有信息(包括秒杀的商品id、秒杀成功状态、成功信息、用户明细),失败就抛出一个我们允许的异常(重复秒杀异常、秒杀结束异常),代码如下:
package org.seckill.dto;
import org.seckill.emuns.SeckillStateEnum;
import org.seckill.entity.SuccessKilled;
/**
* Created by joshul on 2017/2/8.
*/
public class SeckillExecution {
private long seckillId;
//秒杀执行结果状态
private int state;
//状态表示
private String stateInfo;
//秒杀成功对象
private SuccessKilled successKilled;
public SeckillExecution(long seckillId, SeckillStateEnum statEnum, SuccessKilled successKilled) {
this.seckillId = seckillId;
this.state = statEnum.getState();
this.stateInfo = statEnum.getStateInfo();
this.successKilled = successKilled;
}
public SeckillExecution(long seckillId, SeckillStateEnum statEnum) {
this.seckillId = seckillId;
this.state = statEnum.getState();
this.stateInfo = statEnum.getStateInfo();
}
public long getSeckillId() {
return seckillId;
}
public void setSeckillId(long seckillId) {
this.seckillId = seckillId;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getStateInfo() {
return stateInfo;
}
public void setStateInfo(String stateInfo) {
this.stateInfo = stateInfo;
}
public SuccessKilled getSuccessKilled() {
return successKilled;
}
public void setSuccessKilled(SuccessKilled successKilled) {
this.successKilled = successKilled;
}
@Override
public String toString() {
return "SeckillExecution{" +
"seckillId=" + seckillId +
", state=" + state +
", stateInfo='" + stateInfo + '\'' +
", successKilled=" + successKilled +
'}';
}
}
然后需要创建我们在秒杀业务过程中允许的异常,重复秒杀异常RepeatKillException.java:
package org.seckill.exception;
/**
*
*/
public class RepeatKillException extends SeckillException{
public RepeatKillException(String message) {
super(message);
}
public RepeatKillException(String message, Throwable cause) {
super(message, cause);
}
}
秒杀关闭异常SeckillCloseException.java:
package org.seckill.exception;
/**
* Created by joshul on 2017/2/8.
*/
public class SeckillCloseException extends SeckillException{
public SeckillCloseException(String message) {
super(message);
}
public SeckillCloseException(String message, Throwable cause) {
super(message, cause);
}
}
和一个异常包含与秒杀业务所有出现的异常SeckillException.java:
package org.seckill.exception;
/**
* Created by joshul on 2017/2/8.
*/
public class SeckillException extends RuntimeException{
public SeckillException(String message) {
super(message);
}
public SeckillException(String message, Throwable cause) {
super(message, cause);
}
}
到此,接口的工作便完成,接下来进行接口实现类的编码工作。
2.秒杀Service接口的实现
在service包下创建impl包存放它的实现类,SeckillServiceImpl.java,内容如下:
package org.seckill.service.imp;
import org.apache.commons.collections.MapUtils;
import org.seckill.dao.SeckillDao;
import org.seckill.dao.SuccessKilledDao;
import org.seckill.dao.redis.RedisDao;
import org.seckill.dto.Exposer;
import org.seckill.dto.SeckillExecution;
import org.seckill.emuns.SeckillStateEnum;
import org.seckill.entity.Seckill;
import org.seckill.entity.SuccessKilled;
import org.seckill.exception.RepeatKillException;
import org.seckill.exception.SeckillCloseException;
import org.seckill.exception.SeckillException;
import org.seckill.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by joshul on 2017/2/8.
*/
@Service
public class SeckillServiceImp implements SeckillService{
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private SeckillDao seckillDao;
@Autowired
private SuccessKilledDao successKilledDao;
@Autowired
private RedisDao redisDao;
//md5盐值字符串,用于混淆MD5
private final String slat = "545hjh78HJ^*&^<?>13215456321,/.jhghj!@^&5";
public List<Seckill> getSeckillList() {
return seckillDao.queryAll(0,4);
}
public Seckill getById(long seckillId) {
return seckillDao.queryById(seckillId);
}
public Exposer exportSeckillUrl(long seckillId) {
//优化到缓存 先查缓存,然后缓存到redis.
Seckill seckill = redisDao.getSeckill(seckillId);
if(seckill == null){
seckill = seckillDao.queryById(seckillId);
if(seckill == null){
return new Exposer(false, seckillId);
}else {
redisDao.putSeckill(seckill);
}
}
//系统当前时间
Date nowTime = new Date();
Date startTime = seckill.getStartTime();
Date endTime = seckill.getEndTime();
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;
}
@Transactional
/**
* 使用注解控制事务方法的优点:
* 1:开发团队达成一致约定,明确标识事务方法的编程风格。
* 2:保证事务方法的执行时间尽可能短,不要穿插其他的网络操作,RPC/HTTP请求或者剥离到事务方法外部。
* 3:不是所有的方法都需要事务,如只有一条修改操作,只读操作不需要事务。
*/
public SeckillExecution executeSeckill(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{
//记录购买行为
//唯一验证:seckillId,userPhone
int insertCount = successKilledDao.insertSuccessKilled(seckillId,userPhone);
if(insertCount <= 0){
throw new SeckillCloseException("重复秒杀");
} else {
//执行秒杀逻辑:减库存 + 记录购买行为
int updateCount = seckillDao.reduceNumber(seckillId,nowTime);
if(updateCount <= 0){
//重复秒杀
throw new RepeatKillException("秒杀关闭");
} else {
//秒杀成功
SuccessKilled successKilled = successKilledDao.queryByIdWithSeckill(seckillId,userPhone);
return new SeckillExecution(seckillId, SeckillStateEnum.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 SeckillExecution executeSeckillProcedure(long seckillId, long userPhone, String md5) {
if (md5 == null || !md5.equals(getMD5(seckillId))) {
return new SeckillExecution(seckillId, SeckillStateEnum.DATA_REWRITE);
}
Date killTime = new Date();
Map<String, Object> map = new HashMap<String, Object>();
map.put("seckillId", seckillId);
map.put("phone", userPhone);
map.put("killTime", killTime);
map.put("result", null);
//存储过程执行完之后result被赋值
try {
seckillDao.killByProcedure(map);
//获取result
int result = MapUtils.getInteger(map, "result", -2);
if (result==1) {
SuccessKilled sk = successKilledDao.
queryByIdWithSeckill(seckillId, userPhone);
return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS,sk);
}else {
return new SeckillExecution(seckillId, SeckillStateEnum.stateOf(result));
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
return new SeckillExecution(seckillId, SeckillStateEnum.INNER_ERROR);
}
}
}
对上述代码进行分析一下,在return new SeckillExecution(seckillId,1,"秒杀成功",successKilled);代码中,我们返回的state和stateInfo参数信息应该是输出给前端的,但是我们不想在我们的return代码中硬编码这两个参数,所以我们应该考虑用枚举的方式将这些常量封装起来,在org.seckill包下新建一个枚举包enums,创建一个枚举类型SeckillStatEnum.java,内容如下:
package org.seckill.emuns;
/**
* Created by joshul on 2017/2/8.
*/
public enum SeckillStateEnum {
SUCCESS(1,"秒杀成功"),
END(0,"秒杀结束"),
REPEAT_KILL(-1,"重复秒杀"),
INNER_ERROR(-2,"系统异常"),
DATA_REWRITE(-3,"数据篡改");
private int state;
private String stateInfo;
SeckillStateEnum(int state, String stateInfo) {
this.state = state;
this.stateInfo = stateInfo;
}
public int getState() {
return state;
}
public String getStateInfo() {
return stateInfo;
}
public static SeckillStateEnum stateOf(int index) {
for (SeckillStateEnum state : values()) {
if (state.getState() == index) {
return state;
}
}
return null;
}
}
然后修改执行秒杀操作的非业务类SeckillExecution.java里面涉及到state和stateInfo参数的构造方法:
public SeckillExecution(long seckillId, SeckillStateEnum statEnum, SuccessKilled successKilled) {
this.seckillId = seckillId;
this.state = statEnum.getState();
this.stateInfo = statEnum.getStateInfo();
this.successKilled = successKilled;
}
public SeckillExecution(long seckillId, SeckillStateEnum statEnum) {
this.seckillId = seckillId;
this.state = statEnum.getState();
this.stateInfo = statEnum.getStateInfo();
}
目前为止我们Service的实现全部完成,接下来要将Service交给Spring的容器托管,进行一些配置。
3.使用Spring托管Service依赖配置
<?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"
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">
<!--扫描service包下所有使用注解的类型-->
<context:component-scan base-package="cn.codingxiaxw.service"/>
</beans>
后采用注解的方式将Service的实现类加入到Spring IOC容器中:
/@Component @Service @Dao @Controller
@Service
public class SeckillServiceImpl implements SeckillService
4.使用Spring声明式事务配置
声明式事务的使用方式:1.早期使用的方式:ProxyFactoryBean+XMl.2.tx:advice+aop命名空间,这种配置的好处就是一次配置永久生效。3.注解@Transactional的方式。在实际开发中,建议使用第三种对我们的事务进行控制,优点见下面代码中的注释。下面让我们来配置声明式事务,在spring-service.xml中添加对事务的配置:
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据库连接池-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置基于注解的声明式事务
默认使用注解来管理事务行为-->
<tx:annotation-driven transaction-manager="transactionManager"/>
然后在Service实现类的方法中,在需要进行事务声明的方法上加上事务的注解:
/秒杀是否成功,成功:减库存,增加明细;失败:抛出异常,事务回滚
@Transactional
/**
* 使用注解控制事务方法的优点:
* 1.开发团队达成一致约定,明确标注事务方法的编程风格
* 2.保证事务方法的执行时间尽可能短,不要穿插其他网络操作RPC/HTTP请求或者剥离到事务方法外部
* 3.不是所有的方法都需要事务,如只有一条修改操作、只读操作不要事务控制
*/
public SeckillExecution executeSeckill(long seckillId, long userPhone, String md5)
throws SeckillException, RepeatKillException, SeckillCloseException {}
下面针对我们之前做的业务实现类来做集成测试。
在SeckillService接口中使用IDEA快捷键shift+ctrl+T,快速生成junit测试类。Service实现类中前面两个方法很好实现,获取列表或者列表中的一个商品的信息即可,测试如下:
@RunWith(SpringJUnit4ClassRunner.class)
//告诉junit spring的配置文件
@ContextConfiguration({"classpath:spring/spring-dao.xml",
"classpath:spring/spring-service.xml"})
public class SeckillServiceTest {
private final Logger logger= LoggerFactory.getLogger(this.getClass());
@Autowired
private SeckillService seckillService;
@Test
public void getSeckillList() throws Exception {
List<Seckill> seckills=seckillService.getSeckillList();
System.out.println(seckills);
}
@Test
public void getById() throws Exception {
long seckillId=1000;
Seckill seckill=seckillService.getById(seckillId);
System.out.println(seckill);
}
}
重点就是exportSeckillUrl()方法和executeSeckill()方法的测试,接下来我们进行exportSeckillUrl()方法的测试,如下:
@Test
public void exportSeckillUrl() throws Exception {
long seckillId=1000;
Exposer exposer=seckillService.exportSeckillUrl(seckillId);
System.out.println(exposer);
}
控制台中输入如下信息:
Exposer{exposed=false, md5='null', seckillId=1000, now=1480322072410, start=1451577600000, end=1451664000000}
然后相继的测试其他部分
目前为止,Dao层和Service层的集成测试我们都已经完成,接下来进行Web层的开发编码工作,请查看我的下篇文章Java高并发秒杀API之Web层开发。