首先先贏明白service層的作用:Service層主要負(fù)責(zé)業(yè)務(wù)模塊的邏輯應(yīng)用設(shè)計(jì),同樣是先設(shè)計(jì)接口,再設(shè)計(jì)其實(shí)現(xiàn)的類,接著再是spring的配置其實(shí)現(xiàn)的關(guān)聯(lián),這樣就可以在應(yīng)用中調(diào)用service接口來進(jìn)行業(yè)務(wù)處理
1、service接口設(shè)計(jì)
~、前臺(tái)頁面需要顯示參與秒殺商品的信息:getSeckillList(showPage):根據(jù)現(xiàn)實(shí)的頁碼進(jìn)行列表查詢,查詢秒殺記錄
~、點(diǎn)擊相應(yīng)連接后前臺(tái)顯示具體商品信息:getById(sekillId):查詢單個(gè)秒殺記錄
package com.seckill.service;
public interface SeckillService {
/**
* 查詢所有秒殺記錄
* @return
*/
List<Seckill> getSeckillList(int showPage);
/**
* 在每頁顯示5條數(shù)據(jù)情況下
* 獲得總頁數(shù)
*
* @return
*/
int getPageCount();
/**
* 查詢單個(gè)秒殺記錄
* @param seckillId
* @return
*/
Seckill getById(long seckillId);
/**
* 秒殺開啟時(shí)輸出秒殺接口地址
* 否則輸出系統(tǒng)時(shí)間和秒殺時(shí)間
* @param seckillId
*/
Exposer exportSeckillUrl(long seckillId);
/**
* 執(zhí)行秒殺操作,有可能是失敗的,失敗的時(shí)候就拋出異常
* @param seckillId 秒殺的商品Id
* @param userPhone 手機(jī)號(hào)碼
* @param md5 md5加密值
*/
SeckillExecution executeSeckill(long seckillId, long userPhone, String md5)
throws SeckillException,SeckillCloseException,RepeaKillException;
/**
* 執(zhí)行存儲(chǔ)過程操作
* @param seckillId
* @param userPhone
* @param md5
* @return
*/
SeckillExecution executeSeckillProcedure(long seckillId, long userPhone,String md5);
}
當(dāng)開始編寫service接口時(shí),需要思考一個(gè)問題,那就是后臺(tái)反饋給前臺(tái)的數(shù)據(jù)是一個(gè)怎樣的json數(shù)據(jù)?數(shù)字狀態(tài)碼,或者是文字?
這里先解釋幾種對(duì)象:
~、PO: 也就是我們?cè)跒槊恳粡垟?shù)據(jù)庫(kù)表寫一個(gè)實(shí)體的類
~、VO, 對(duì)某個(gè)頁面或者展現(xiàn)層所需要的數(shù)據(jù),封裝成一個(gè)實(shí)體類
~、BO, 就是業(yè)務(wù)對(duì)象,我也不是很了解
~、DTO, 跟VO的概念有點(diǎn)混淆,也是相當(dāng)于頁面需要的數(shù)據(jù)封裝成一個(gè)實(shí)體類
~、POJO, 簡(jiǎn)單的無規(guī)則java對(duì)象
了解了這幾種對(duì)象,便可以明白,我們需要向前臺(tái)返回的可以是DTO對(duì)象,后臺(tái)對(duì)所需要返回的數(shù)據(jù)進(jìn)行封裝。
因此對(duì)于service接口中的Esposer和SeckillExecution 對(duì)象便可以解釋,以及相應(yīng)的異常對(duì)象
com.seckill.dto.Exposer
com.seckill.dto.SeckillExecution
/**
* 秒殺開啟時(shí)輸出秒殺接口地址
* 否則輸出系統(tǒng)時(shí)間和秒殺時(shí)間
* @param seckillId
*/
Exposer exportSeckillUrl(long seckillId);
/**
* 執(zhí)行秒殺操作,有可能是失敗的,失敗的時(shí)候就拋出異常
* @param seckillId 秒殺的商品Id
* @param userPhone 手機(jī)號(hào)碼
* @param md5 md5加密值
*/
SeckillExecution executeSeckill(long seckillId, long userPhone, String md5)
throws SeckillException,SeckillCloseException,RepeaKillException;
Exposer如下:(編寫時(shí)也要想好Exposer包含的變量以及不同情況下對(duì)應(yīng)的構(gòu)造函數(shù))
package com.seckill.dto;
public class Exposer {
@Override
public String toString() {
return "Exposer [exposed=" + exposed + ", md5=" + md5 + ", seckillId=" + seckillId + ", now=" + now + ", start="
+ start + ", end=" + end + "]";
}
//無參構(gòu)造函數(shù)
public Exposer() {
// Auto-generated constructor stub
}
//是否開啟秒殺
private boolean exposed;
// 一種加密措施
private String md5;
//秒殺商品id
private long seckillId;
// 系統(tǒng)當(dāng)前時(shí)間
private long now;
//開啟時(shí)間
private long start;
//結(jié)束時(shí)間
private long end;
/**
* 當(dāng)秒殺時(shí)間不符合時(shí),返回的數(shù)據(jù)
* @param exposed false狀態(tài)
* @param seckillId 商品ID
* @param now 當(dāng)前系統(tǒng)時(shí)間(服務(wù)器時(shí)間)
* @param start 秒殺開啟時(shí)間
* @param end 秒殺結(jié)束時(shí)間
*/
public Exposer(boolean exposed, Long seckillId,long now, long start, long end) {
super();
this.seckillId = seckillId;
this.exposed = exposed;
this.now = now;
this.start = start;
this.end = end;
}
/**
* 該商品符合秒殺時(shí)返回的數(shù)據(jù)
* @param exposed 狀態(tài)
* @param md5 一種鹽值加密數(shù)據(jù)
* @param seckillId 秒殺商品id
*/
public Exposer(boolean exposed, String md5, long seckillId) {
super();
this.exposed = exposed;
this.md5 = md5;
this.seckillId = seckillId;
}
/**
* 秒殺商品不存在時(shí)返回的數(shù)據(jù)
* @param exposed
* @param seckillId
*/
public Exposer(boolean exposed, long seckillId) {
super();
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;
}
}
SeckillExecution:執(zhí)行秒殺后后臺(tái)返回給前臺(tái)的數(shù)據(jù)封裝對(duì)象
package com.seckill.dto;
import com.seckill.entity.SuccessKilled;
import com.seckill.enums.SeckillStateEnum;
public class SeckillExecution {
public SeckillExecution() {
//Auto-generated constructor stub
}
// 商品Id
private long seckillId;
// 秒殺結(jié)果的狀態(tài)
private int state;
/* 狀態(tài)的明文標(biāo)示 */
private String stateInfo;
/* 當(dāng)秒殺成功時(shí),需要傳遞秒殺結(jié)果的對(duì)象回去 */
private SuccessKilled successKilled;
/* 秒殺成功返回的實(shí)體 */
public SeckillExecution(long seckillId, SeckillStateEnum stateEnum, SuccessKilled successKilled) {
super();
this.seckillId = seckillId;
this.state = stateEnum.getState();
this.stateInfo = stateEnum.getStateInfo();
this.successKilled = successKilled;
}
/* 秒殺失敗時(shí)返回的實(shí)體,沒有秒殺結(jié)果的對(duì)象 */
public SeckillExecution(long seckillId, SeckillStateEnum stateEnum) {
super();
this.seckillId = seckillId;
this.state = stateEnum.getState();
this.stateInfo = stateEnum.getStateInfo();
}
@Override
public String toString() {
return "SeckillException [seckillId=" + seckillId + ", state=" + state + ", stateIofo=" + stateInfo
+ ", successKilled=" + successKilled + "]";
}
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;
}
}
定義秒殺過程中可能會(huì)出現(xiàn)的異常:
~、定義一個(gè)基礎(chǔ)異常,所有的異常都繼承這個(gè)異常
SeckillException :
package com.seckill.exception;
public class SeckillException extends RuntimeException {
public SeckillException() {
}
public SeckillException(String message) {
super(message);
}
public SeckillException(String message, Throwable cause) {
super(message, cause);
}
}
~、定義重復(fù)秒殺異常:
package com.seckill.exception;
/**
* 重復(fù)秒殺異常,不需要我們手動(dòng)去try catch
* @author hyh47
*
*/
public class RepeaKillException extends SeckillException{
public RepeaKillException() {
}
public RepeaKillException(String message){
super(message);
}
public RepeaKillException(String message,Throwable cause){
super(message, cause);
}
}
~、定義秒殺關(guān)閉異常
package com.seckill.exception;
/**
* 秒殺已經(jīng)關(guān)閉異常,當(dāng)秒殺結(jié)束就會(huì)出現(xiàn)這個(gè)異常
* @author hyh47
*
*/
public class SeckillCloseException extends SeckillException{
public SeckillCloseException() {
}
public SeckillCloseException(String message){
super(message);
}
public SeckillCloseException(String message, Throwable cause){
super(message, cause);
}
}
2、service接口實(shí)現(xiàn)
@Service
public class SeckillServiceImpl implements SeckillService {
/*日志記錄*/
private org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());
/*自定義用于md5加密的鹽值*/
private final String salt = "ljflajvoia332131ADSFJJL(&(*(*#@";
final int pageSize = 5;//單頁顯示的數(shù)量
//注入service依賴
@Autowired
private SeckillDao seckillDao;
@Autowired
private SuccessKilledDao successKilledDao;
@Autowired
private RedisDao redisDao;
public SeckillServiceImpl() {
// Auto-generated constructor stub
}
/**
* 查詢?nèi)康拿霘⒂涗? *
* @return 數(shù)據(jù)庫(kù)中所有的秒殺記錄
*/
/*
pageSize(每個(gè)頁面所顯示的記錄數(shù))、
pageCount(頁面的總數(shù))、
showPage(目前顯示第幾頁)、
recordCount(總的記錄數(shù))
*/
@Override
public List<Seckill> getSeckillList(int showPage) {
// Auto-generated method stub
return seckillDao.queryAll((showPage - 1) * pageSize, pageSize);
}
@Override
public int getPageCount() {
int recordCount = seckillDao.querySeckillNumber();//總數(shù)
int pageCount = (recordCount % pageSize == 0) ? (recordCount / pageSize) : (recordCount / pageSize + 1);
return pageCount;
}
/**
* 查詢秒殺記錄,通過商品Id
*/
@Override
public Seckill getById(long seckillId) {
// Auto-generated method stub
return seckillDao.queryById(seckillId);
}
@Override
@Transactional
/**
* 使用注解控制事務(wù)方法的優(yōu)點(diǎn):
* 1:開發(fā)團(tuán)隊(duì)打成一致約定,明確標(biāo)注事務(wù)方法的編程風(fēng)格
* 2:保證事務(wù)方法的執(zhí)行時(shí)間盡可能短,不穿插其他網(wǎng)絡(luò)操作,RPC/HTTP請(qǐng)求或者剝離到事務(wù)方法外部
* 3:不是所有的方法都需要事務(wù),比如只有一條修改操作,或者只讀操作不需要事務(wù)控制
*/
public Exposer exportSeckillUrl(long seckillId) {
// Auto-generated method stub
/*Seckill seckill = seckillDao.queryById(seckillId);
if (seckill == null){
return new Exposer(false,seckillId);
}*/
Seckill seckill = redisDao.getSeckill(seckillId);
if (seckill == null) {
//訪問數(shù)據(jù)庫(kù)讀取數(shù)據(jù)
seckill = seckillDao.queryById(seckillId);
if (seckill == null) {
return new Exposer(false, seckillId);
} else {
//放入redis中
redisDao.putSeckill(seckill);
}
}
Date startTime = seckill.getStartTime();
Date endTime = seckill.getEndTime();
//當(dāng)前系統(tǒng)時(shí)間
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 + "/" + salt;
String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
return md5;
}
@Override
public SeckillExecution executeSeckill(long seckillId, long userPhone, String md5)
throws SeckillException, SeckillCloseException, RepeaKillException {
//在這一系列操作中,對(duì)應(yīng)事務(wù),return是commit,拋異常是rollback
try {
if (md5 == null || !md5.equals(getMD5(seckillId))) {
logger.error("秒殺數(shù)據(jù)被篡改");
throw new SeckillException("seckill data rewrite");
}
//執(zhí)行秒殺邏輯: 減庫(kù)存+記錄購(gòu)買行為
Date nowTime = new Date();
//記錄購(gòu)買行為
int insertCount = successKilledDao.insertSuccessKilled(seckillId, userPhone);
//唯一:seckillId,userPhone
if (insertCount <= 0) {
logger.warn("不允許重復(fù)秒殺");
throw new RepeaKillException("repeaKill !!");
} else {
//減庫(kù)存,熱點(diǎn)商品競(jìng)爭(zhēng)
int updateCount = seckillDao.reduceNumber(seckillId, nowTime);
if (updateCount <= 0) {
//沒有更新記錄,秒殺結(jié)束,可能時(shí)間結(jié)束也可能庫(kù)存為零,rollback
logger.warn("沒有更新數(shù)據(jù)庫(kù)記錄,秒殺已經(jīng)結(jié)束了");
throw new SeckillCloseException("seckill is closed");
} else {
//秒殺成功,commit
SuccessKilled successkilled = successKilledDao.queryByIdWithSeckill(seckillId, userPhone);
return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS, successkilled);
}
}
} catch (SeckillCloseException | RepeaKillException e1) {
throw e1;
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new SeckillException("seckill inner error:" + e.getMessage());
}
}
@Override
public SeckillExecution executeSeckillProcedure(long seckillId, long userPhone, String md5) {
if (md5 == null || !md5.equals(getMD5(seckillId))) {
return new SeckillExecution(seckillId, SeckillStateEnum.DATE_PEWRITER);
}
Date killTime = new Date();
Map<String, Object> map = new HashMap<>();
map.put("seckillId", seckillId);
map.put("phone", userPhone);
map.put("killTime", killTime);
map.put("result", null);
//執(zhí)行存儲(chǔ)過程,result被復(fù)制
try {
seckillDao.killByProcedure(map);
//獲取result
int result = MapUtils.getInteger(map, "result", -2);
if (result == 1) {
SuccessKilled successKilled = successKilledDao.queryByIdWithSeckill(seckillId, userPhone);
return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS, successKilled);
} else {
return new SeckillExecution(seckillId, SeckillStateEnum.stateOf(result));
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
return new SeckillExecution(seckillId, SeckillStateEnum.INNER_ERROR);
}
}
}
在這里我們捕獲了運(yùn)行時(shí)異常,這樣做的原因就是Spring的事物默認(rèn)就是發(fā)生了RuntimeException才會(huì)回滾,可以檢測(cè)出來的異常是不會(huì)導(dǎo)致事物的回滾的,這樣的目的就是你明知道這里會(huì)發(fā)生異常,所以你一定要進(jìn)行處理.如果只是為了讓編譯通過的話,那捕獲異常也沒多意思,所以這里要注意事物的回滾.
然后我們還發(fā)現(xiàn)這里存在硬編碼的現(xiàn)象,就是返回各種字符常量,例如秒殺成功,秒殺失敗等等,這些字符串時(shí)可以被重復(fù)使用的,而且這樣維護(hù)起來也不方便,要到處去類里面尋找這樣的字符串,所有我們使用枚舉類來管理這樣狀態(tài),在com.seckill包下建立enum包,專門放置枚舉類,然后再建立SeckillStateEnum枚舉類:
此處關(guān)于秒殺結(jié)果的集中狀態(tài),采用枚舉類進(jìn)行封裝:
com.seckill.enums.SeckillStateEnum
package com.seckill.enums;
/**
* 使用枚舉表述常量數(shù)據(jù)字段
* @author hyh47
*
*/
public enum SeckillStateEnum {
SUCCESS(1,"秒殺成功"),
END(0,"秒殺結(jié)束"),
REPEAT_KILL(-1,"重復(fù)秒殺"),
INNER_ERROR(-2,"系統(tǒng)異常"),
DATE_PEWRITER(-3,"數(shù)據(jù)篡改");
private int state;
private String stateInfo;
public int getState() {
return state;
}
public String getStateInfo() {
return stateInfo;
}
private SeckillStateEnum(int state, String stateInfo) {
this.state = state;
this.stateInfo = stateInfo;
}
public static SeckillStateEnum stateOf(int index){
for (SeckillStateEnum state: values()){
if (state.getState() == index){
return state;
}
}
return null;
}
}
3、進(jìn)行service層的spring配置,注入service
~、掃描service包下的注解
~、配置事務(wù),在事務(wù)中注入數(shù)據(jù)庫(kù)連接池
~、開啟基于注解的聲明式事務(wù)
<?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-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd ">
<!--掃描service包下所有使用注解的類型 -->
<context:component-scan base-package="com.seckill.service"></context:component-scan>
<!-- 配置事務(wù)管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入數(shù)據(jù)庫(kù)連接池 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 開啟基于注解的聲明式事務(wù) -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
在配置過程中應(yīng)該注意xml的頭信息
4、service層的測(cè)試
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/spring-dao.xml", "classpath:spring/spring-service.xml"})
public class SeckillServiceTest {
private org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());
@Resource
private SeckillService seckillService;
@Test
public void executeSeckillProcedure() throws Exception {
long seckillId = 1001L;
long userphone = 18126745520L;
Exposer exposer = seckillService.exportSeckillUrl(seckillId);
if (exposer.isExposed()) {
String md5 = exposer.getMd5();
SeckillExecution execution = seckillService.executeSeckillProcedure(seckillId, userphone, md5);
logger.info(execution.getStateInfo());
}
}
@Test
public void getPageCount() throws Exception {
System.out.println(seckillService.getPageCount());
}
@Test
public void getSeckillList() throws Exception {
List<Seckill> list = seckillService.getSeckillList(1);
logger.info(list.toString());
System.out.println(list.toString());
}
@Test
public void getById() throws Exception {
long seckillId = 1000L;
Seckill seckill = seckillService.getById(seckillId);
System.out.println(seckill.toString());
}
@Test
public void exportSeckillUrl() throws Exception {
long seckillId = 1000L;
Exposer exposer = seckillService.exportSeckillUrl(seckillId);
System.out.println(exposer.toString());
}
@Test
public void executeSeckill() throws Exception {
long seckillId = 1000L;
long userPhone = 125906441181L;
String md5 = "ab977232c7bfb60cf33df852e171edd9";
try {
SeckillExecution seckillExecution = seckillService.executeSeckill(seckillId, userPhone, md5);
logger.info("result={}", seckillExecution);
} catch (SeckillCloseException e) {
logger.error(e.getMessage());
} catch (RepeaKillException e) {
logger.error(e.getMessage());
} catch (SeckillException e) {
logger.error(e.getMessage());
}
}