源碼:https://github.com/joshul/seckill
開始Service層的編碼之前绑蔫,我們首先需要進(jìn)行Dao層編碼之后的思考:在Dao層我們只完成了針對表的相關(guān)操作包括寫了接口方法和映射文件中的sql語句穗酥,并沒有編寫邏輯的代碼喧锦,例如對多個Dao層方法的拼接,當(dāng)我們用戶成功秒殺商品時我們需要進(jìn)行商品的減庫存操作(調(diào)用SeckillDao接口)和增加用戶明細(xì)(調(diào)用SuccessKilledDao接口)坤次,這些邏輯我們都需要在Service層完成凿可。這也是一些初學(xué)者容易出現(xiàn)的錯誤,他們喜歡在Dao層進(jìn)行邏輯的編寫术裸,其實Dao就是數(shù)據(jù)訪問的縮寫,它只進(jìn)行數(shù)據(jù)的訪問操作亭枷,接下來我們便進(jìn)行Service層代碼的編寫袭艺。
1. 秒殺Service接口設(shè)計
在org.seckill包下創(chuàng)建一個service包用于存放我們的Service接口和其實現(xiàn)類,創(chuàng)建一個exception包用于存放service層出現(xiàn)的異常例如重復(fù)秒殺商品異常叨粘、秒殺已關(guān)閉等異常猾编,一個dto包作為傳輸層,dto和entity的區(qū)別在于:entity用于業(yè)務(wù)數(shù)據(jù)的封裝,而dto用于完成web和service層的數(shù)據(jù)傳遞升敲。
首先創(chuàng)建我們Service接口答倡,里面的方法應(yīng)該是按”使用者”(程序員)的角度去設(shè)計,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;
/**
* 業(yè)務(wù)接口:站在"使用者"角度設(shè)計接口
* 三個方面:方法定義粒度瘪撇,參數(shù),返回類型(return 類型/異常)
*/
public interface SeckillService {
/**
* 查詢所有秒殺記錄
* @return List<Seckill>
*/
List<Seckill> getSeckillList();
/**
* 查詢單個秒殺記錄
* @param seckillId
* @return Seckill
*/
Seckill getById(long seckillId);
/**
* 秒殺開啟時輸出秒殺接口地址,
* 否則輸出系統(tǒng)時間個秒殺時間
* @param seckillId
* @return Exposer
*/
Exposer exportSeckillUrl(long seckillId);
/**
* 執(zhí)行秒殺操作
* @param seckillId
* @param userPhone
* @param md5
* @return SeckillExecution
*/
SeckillExecution executeSeckill(long seckillId, long userPhone, String md5)
throws SeckillException,RepeatKillException,SeckillCloseException;
/**
* 存儲過程執(zhí)行秒殺
* @param seckillId
* @param userPhone
* @param md5
* @return
* SeckillExecution
*
*/
SeckillExecution executeSeckillProcedure(long seckillId,long userPhone,String md5);
}
該接口中前面兩個方法返回的都是跟我們業(yè)務(wù)相關(guān)的對象港庄,而后兩個方法返回的對象與業(yè)務(wù)不相關(guān)倔既,這兩個對象我們用于封裝service和web層傳遞的數(shù)據(jù),方法的作用我們已在注釋中給出攘轩。相應(yīng)在的dto包中創(chuàng)建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;
//系統(tǒng)當(dāng)前時間(毫秒)
private long now;
//開啟時間
private long start;
//結(jié)束時間
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瞳秽、秒殺成功狀態(tài)、成功信息率翅、用戶明細(xì))练俐,失敗就拋出一個我們允許的異常(重復(fù)秒殺異常、秒殺結(jié)束異常),代碼如下:
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;
//秒殺執(zhí)行結(jié)果狀態(tài)
private int state;
//狀態(tài)表示
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 +
'}';
}
}
然后需要創(chuàng)建我們在秒殺業(yè)務(wù)過程中允許的異常冕臭,重復(fù)秒殺異常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);
}
}
秒殺關(guān)閉異常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);
}
}
和一個異常包含與秒殺業(yè)務(wù)所有出現(xiàn)的異常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);
}
}
到此腺晾,接口的工作便完成,接下來進(jìn)行接口實現(xiàn)類的編碼工作辜贵。
2.秒殺Service接口的實現(xiàn)
在service包下創(chuàng)建impl包存放它的實現(xiàn)類悯蝉,SeckillServiceImpl.java,內(nèi)容如下:
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) {
//優(yōu)化到緩存 先查緩存鼻由,然后緩存到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);
}
}
//系統(tǒng)當(dāng)前時間
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());
}
//轉(zhuǎn)化特定字符串的過程,不可逆
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
/**
* 使用注解控制事務(wù)方法的優(yōu)點:
* 1:開發(fā)團(tuán)隊達(dá)成一致約定厚棵,明確標(biāo)識事務(wù)方法的編程風(fēng)格蕉世。
* 2:保證事務(wù)方法的執(zhí)行時間盡可能短,不要穿插其他的網(wǎng)絡(luò)操作婆硬,RPC/HTTP請求或者剝離到事務(wù)方法外部狠轻。
* 3:不是所有的方法都需要事務(wù),如只有一條修改操作彬犯,只讀操作不需要事務(wù)哈误。
*/
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("重復(fù)秒殺");
} else {
//執(zhí)行秒殺邏輯:減庫存 + 記錄購買行為
int updateCount = seckillDao.reduceNumber(seckillId,nowTime);
if(updateCount <= 0){
//重復(fù)秒殺
throw new RepeatKillException("秒殺關(guān)閉");
} 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);
//所有編譯器異常 轉(zhuǎn)化為運行期異常
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);
//存儲過程執(zhí)行完之后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);
}
}
}
對上述代碼進(jìn)行分析一下,在return new SeckillExecution(seckillId,1,"秒殺成功",successKilled);代碼中躏嚎,我們返回的state和stateInfo參數(shù)信息應(yīng)該是輸出給前端的蜜自,但是我們不想在我們的return代碼中硬編碼這兩個參數(shù),所以我們應(yīng)該考慮用枚舉的方式將這些常量封裝起來卢佣,在org.seckill包下新建一個枚舉包enums重荠,創(chuàng)建一個枚舉類型SeckillStatEnum.java,內(nèi)容如下:
package org.seckill.emuns;
/**
* Created by joshul on 2017/2/8.
*/
public enum SeckillStateEnum {
SUCCESS(1,"秒殺成功"),
END(0,"秒殺結(jié)束"),
REPEAT_KILL(-1,"重復(fù)秒殺"),
INNER_ERROR(-2,"系統(tǒng)異常"),
DATA_REWRITE(-3,"數(shù)據(jù)篡改");
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;
}
}
然后修改執(zhí)行秒殺操作的非業(yè)務(wù)類SeckillExecution.java里面涉及到state和stateInfo參數(shù)的構(gòu)造方法:
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的實現(xiàn)全部完成虚茶,接下來要將Service交給Spring的容器托管戈鲁,進(jìn)行一些配置。
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的實現(xiàn)類加入到Spring IOC容器中:
/@Component @Service @Dao @Controller
@Service
public class SeckillServiceImpl implements SeckillService
4.使用Spring聲明式事務(wù)配置
聲明式事務(wù)的使用方式:1.早期使用的方式:ProxyFactoryBean+XMl.2.tx:advice+aop命名空間嘹叫,這種配置的好處就是一次配置永久生效婆殿。3.注解@Transactional的方式。在實際開發(fā)中罩扇,建議使用第三種對我們的事務(wù)進(jìn)行控制婆芦,優(yōu)點見下面代碼中的注釋怕磨。下面讓我們來配置聲明式事務(wù),在spring-service.xml中添加對事務(wù)的配置:
<!--配置事務(wù)管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入數(shù)據(jù)庫連接池-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置基于注解的聲明式事務(wù)
默認(rèn)使用注解來管理事務(wù)行為-->
<tx:annotation-driven transaction-manager="transactionManager"/>
然后在Service實現(xiàn)類的方法中消约,在需要進(jìn)行事務(wù)聲明的方法上加上事務(wù)的注解:
/秒殺是否成功肠鲫,成功:減庫存,增加明細(xì)或粮;失敗:拋出異常导饲,事務(wù)回滾
@Transactional
/**
* 使用注解控制事務(wù)方法的優(yōu)點:
* 1.開發(fā)團(tuán)隊達(dá)成一致約定,明確標(biāo)注事務(wù)方法的編程風(fēng)格
* 2.保證事務(wù)方法的執(zhí)行時間盡可能短氯材,不要穿插其他網(wǎng)絡(luò)操作RPC/HTTP請求或者剝離到事務(wù)方法外部
* 3.不是所有的方法都需要事務(wù)渣锦,如只有一條修改操作、只讀操作不要事務(wù)控制
*/
public SeckillExecution executeSeckill(long seckillId, long userPhone, String md5)
throws SeckillException, RepeatKillException, SeckillCloseException {}
下面針對我們之前做的業(yè)務(wù)實現(xiàn)類來做集成測試氢哮。
在SeckillService接口中使用IDEA快捷鍵shift+ctrl+T袋毙,快速生成junit測試類。Service實現(xiàn)類中前面兩個方法很好實現(xiàn)命浴,獲取列表或者列表中的一個商品的信息即可娄猫,測試如下:
@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()方法的測試,接下來我們進(jìn)行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層的集成測試我們都已經(jīng)完成,接下來進(jìn)行Web層的開發(fā)編碼工作碍讯,請查看我的下篇文章Java高并發(fā)秒殺API之Web層開發(fā)悬蔽。