文章所用例子參考慕課網相關課程。css
使用IDEA建立一個maven的webapp項目,建好相應的項目結構。前端
mainjava
java:java源碼mysql
com.dct.seckillDemo:包名,通常爲groupId+artifactIdgit
resources程序員
webappgithub
testweb
而後導入項目依賴的jar包
pom.xmlajax
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.dct</groupId> <artifactId>seckillDemo</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>seckillDemo Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!--補全項目依賴--> <!--1.日誌 java日誌有:slf4j,log4j,logback,common-logging slf4j:是規範/接口 日誌實現:log4j,logback,common-logging 使用:slf4j+logback --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.1.1</version> </dependency> <!--實現slf4j接口並整合--> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.1</version> </dependency> <!--1.數據庫相關依賴--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> <scope>runtime</scope> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <!--2.dao框架:MyBatis依賴--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <!--mybatis自身實現的spring整合依賴--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.3</version> </dependency> <!--3.Servlet web相關依賴--> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!--4:spring依賴--> <!--1)spring核心依賴--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.7.RELEASE</version> </dependency> <!--2)spring dao層依賴--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.1.7.RELEASE</version> </dependency> <!--3)springweb相關依賴--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.7.RELEASE</version> </dependency> <!--4)spring test相關依賴--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.1.7.RELEASE</version> </dependency> </dependencies> <build> <finalName>seckillDemo</finalName> </build> </project>
下面開始進行整合SSM,首進行mybatis和spring的整合。spring
在resources下新建jdbc.properties和mybatis-config.xml文件。
jdbc.properties(數據庫鏈接相關參數)
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/seckill?useUnicode=true&characterEncoding=utf-8 jdbc.username=root jdbc.password=root
mybatis-config.xml(mybatis全局屬性的配置)
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--配置全局屬性--> <settings> <!--使用jdbc的getGeneratekeys獲取自增主鍵值--> <setting name="useGeneratedKeys" value="true"/> <!--使用列別名替換列名 默認值爲true select name as title(實體中的屬性名是title) form table; 開啓後mybatis會自動幫咱們把表中name的值賦到對應實體的title屬性中 --> <setting name="useColumnLabel" value="true"/> <!--開啓駝峯命名轉換Table:create_time到 Entity(createTime)--> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> </configuration>
而後在spring包下新建spring-dao.xml文件,進行spring和mybatis的整合配置。
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" 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"> <!--配置整合mybatis過程 1.配置數據庫相關參數--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--2.數據庫鏈接池--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!--配置鏈接池屬性--> <property name="driverClass" value="${jdbc.driver}" /> <!-- 基本屬性 url、user、password --> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!--c3p0私有屬性--> <property name="maxPoolSize" value="30"/> <property name="minPoolSize" value="10"/> <!--關閉鏈接後不自動commit--> <property name="autoCommitOnClose" value="false"/> <!--獲取鏈接超時時間--> <property name="checkoutTimeout" value="1000"/> <!--當獲取鏈接失敗重試次數--> <property name="acquireRetryAttempts" value="2"/> </bean> <!--約定大於配置--> <!--3.配置SqlSessionFactory對象--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--往下才是mybatis和spring真正整合的配置--> <!--注入數據庫鏈接池--> <property name="dataSource" ref="dataSource"/> <!--配置mybatis全局配置文件:mybatis-config.xml--> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!--掃描entity包,使用別名,多個用;隔開--> <property name="typeAliasesPackage" value="com.dct.seckillDemo.entity"/> <!--掃描sql配置文件:mapper須要的xml文件--> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!--4:配置掃描Dao接口包,動態實現DAO接口,注入到spring容器--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--注入SqlSessionFactory--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!-- 給出須要掃描的Dao接口--> <!--<property name="basePackage" value="com.dct.seckillDemo.dao"/>--> </bean> <!--掃描dao包下全部使用註解的類型--> <context:component-scan base-package="com.dct.seckillDemo.dao"/> </beans>
在spring包下新建spring-service.xml文件,配置service層。
spring-service.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.dct.seckillDemo.service"/> <!--配置事務管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--注入數據庫鏈接池--> <property name="dataSource" ref="dataSource"/> </bean> <!--配置基於註解的聲明式事務 默認使用註解來管理事務行爲--> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
在spring包下新建spring-web.xml文件,配置控制器層。
spring-web.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:mvc="http://www.springframework.org/schema/mvc" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--配置spring mvc--> <!--1,開啓springmvc註解模式 a.自動註冊DefaultAnnotationHandlerMapping,AnnotationMethodHandlerAdapter b.默認提供一系列的功能:數據綁定,數字和日期的format@NumberFormat,@DateTimeFormat c:xml,json的默認讀寫支持--> <mvc:annotation-driven/> <!--2.靜態資源默認servlet配置--> <!-- 1).加入對靜態資源處理:js,gif,png 2).容許使用 "/" 作總體映射 --> <mvc:default-servlet-handler/> <!--3:配置JSP 顯示ViewResolver--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!--4:掃描web相關的controller--> <context:component-scan base-package="com.dct.seckillDemo.web"/> </beans>
配置web.xml文件
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0" metadata-complete="true"> <!--用maven建立的web-app須要修改servlet的版本爲3.1--> <!--配置DispatcherServlet--> <servlet> <servlet-name>seckill-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置SpringMVC 須要配置的文件 spring-dao.xml,spring-service.xml,spring-web.xml Mybites -> spring -> springMvc --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-*.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>seckill-dispatcher</servlet-name> <!--默認匹配全部請求--> <url-pattern>/</url-pattern> </servlet-mapping> <!--過濾器,解決字符編碼問題--> <filter> <description>字符集過濾器</description> <filter-name>encodingFilter</filter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <description>字符集編碼</description> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
目前爲止,SSM整合工做就已經完成,項目目錄結構以下。
SSM框架應用示例--秒殺系統
首先新建數據庫及相應的數據表,在main下新建一個sql包,而後新建一個schema.sql文件
schema.sql
-- 數據庫初始化腳本 -- 建立數據庫 CREATE DATABASE seckill; -- 使用數據庫,只有INNODb支持事務 use seckill; CREATE TABLE seckill( `seckill_id` BIGINT NOT NUll AUTO_INCREMENT COMMENT '商品庫存ID', `name` VARCHAR(120) NOT NULL COMMENT '商品名稱', `number` int NOT NULL COMMENT '庫存數量', `start_time` TIMESTAMP NOT NULL COMMENT '秒殺開始時間', `end_time` TIMESTAMP NOT NULL COMMENT '秒殺結束時間', `create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間', PRIMARY KEY (seckill_id), key idx_start_time(start_time), key idx_end_time(end_time), key idx_create_time(create_time) )ENGINE=INNODB AUTO_INCREMENT=10000 DEFAULT CHARSET=utf8 COMMENT='秒殺庫存表'; -- 初始化數據 INSERT into seckill(name,number,start_time,end_time) VALUES ('1000元秒殺iphone6',100,'2016-01-01 00:00:00','2016-01-02 00:00:00'), ('800元秒殺ipad',200,'2016-01-01 00:00:00','2016-01-02 00:00:00'), ('6600元秒殺mac book pro',300,'2016-01-01 00:00:00','2016-01-02 00:00:00'), ('7000元秒殺iMac',400,'2016-01-01 00:00:00','2016-01-02 00:00:00'); -- 秒殺成功明細表 -- 用戶登陸認證相關信息(簡化爲手機號) CREATE TABLE success_killed( `seckill_id` BIGINT NOT NULL COMMENT '秒殺商品ID', `user_phone` BIGINT NOT NULL COMMENT '用戶手機號', `state` TINYINT NOT NULL DEFAULT -1 COMMENT '狀態標識:-1:無效 0:成功 1:已付款 2:已發貨', `create_time` TIMESTAMP NOT NULL COMMENT '建立時間', PRIMARY KEY(seckill_id,user_phone),/*聯合主鍵*/ KEY idx_create_time(create_time) )ENGINE=INNODB DEFAULT CHARSET=utf8 COMMENT='秒殺成功明細表'; -- SHOW CREATE TABLE seckill;#顯示錶的建立信息
dao層開發
在entity包中新建兩個實體類,屬性分別與數據表一一對應
Seckill.java
public class Seckill { private long seckillId; private String name; private int number; //該註解處理日期的格式化 @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date startTime; @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date endTime; @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date createTime; public Seckill(){ } public Seckill(String name, int number, Date startTime, Date endTime) { this.name = name; this.number = number; this.startTime = startTime; this.endTime = endTime; } public long getSeckillId() { return seckillId; } public void setSeckillId(long seckillId) { this.seckillId = seckillId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { return "Seckill{" + "seckillId=" + seckillId + ", name='" + name + '\'' + ", number=" + number + ", startTime=" + startTime + ", endTime=" + endTime + ", createTime=" + createTime + '}'; } }
SuccessKilled.java
public class SuccessKilled { private long seckillId; private long userPhone; private short state; private Date createTime; //省略getter,setter和toString方法 }
在dao包下新建兩個接口,定義數據庫操做相關方法
seckillDao.java
@Repository public interface SeckillDao { /** * 減庫存 * @param seckillId * @param killTime * @return 若是影響行數>1,表示更新庫存的記錄行數 */ int reduceNumber(@Param("seckillId") long seckillId, @Param("killTime") Date killTime); /** * 根據id查詢秒殺的商品信息 * @param seckillId * @return */ Seckill queryById(long seckillId); /** * 根據偏移量查詢秒殺商品列表 * @param offset * @param limit * @return */ List<Seckill> queryAll(@Param("offset") int offset, @Param("limit") int limit); // 添加秒殺物品 boolean addItem(Seckill seckill); // 刪除秒殺物品 boolean deleteById(long seckillId); // 更新秒殺物品 boolean updateItem(Seckill seckill); }
SuccessKilledDao.java
@Repository public interface SuccessKilledDao { /** * 插入購買明細,可過濾重複 * @param seckillId * @param userPhone * @return插入的行數 */ int insertSuccessKilled(@Param("seckillId") long seckillId, @Param("userPhone") long userPhone); /** * 根據秒殺商品的id查詢明細SuccessKilled對象(該對象攜帶了Seckill秒殺產品對象) * @param seckillId * @return */ SuccessKilled queryByIdWithSeckill(@Param("seckillId") long seckillId, @Param("userPhone") long userPhone); }
在resources包下的mapper保重建立xml文件,實現dao包接口中的方法。
SeckillDao.xml
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--包名與dao包中的接口名對應--> <mapper namespace="com.dct.seckillDemo.dao.SeckillDao"> <!--目的:爲dao接口方法提供sql語句配置 即針對dao接口中的方法編寫咱們的sql語句--> <!-- id與接口中的方法名一致 parameterType:參數類型,與接口方法中的參數類型一致;對於多個參數,可不寫參數類型,但在dao接口中要用@Param註解 resultType:返回值類型, --> <update id="reduceNumber"> UPDATE seckill SET number = number-1 WHERE seckill_id=#{seckillId} AND start_time <![CDATA[ <= ]]> #{killTime} AND end_time >= #{killTime} AND number > 0; </update> <select id="queryById" resultType="Seckill" parameterType="long"> SELECT * FROM seckill WHERE seckill_id=#{seckillId} </select> <select id="queryAll" resultType="Seckill"> SELECT * FROM seckill ORDER BY create_time DESC limit #{offset},#{limit} </select> <insert id="addItem" parameterType="Seckill"> INSERT INTO seckill(name,number,start_time,end_time) VALUES (#{name},#{number},#{startTime},#{endTime}) </insert> <delete id="deleteById" parameterType="long"> DELETE FROM seckill WHERE seckill_id=#{seckillId} </delete> <update id="updateItem" parameterType="Seckill"> UPDATE seckill set name=#{name},number=#{number},start_time=#{startTime},end_time=#{endTime} WHERE seckill_id=#{seckillId} </update> </mapper>
SuccessKilledDao.xml
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.dct.seckillDemo.dao.SuccessKilledDao"> <insert id="insertSuccessKilled"> <!--當出現主鍵衝突時(即重複秒殺時),會報錯;不想讓程序報錯,加入ignore--> INSERT ignore INTO success_killed(seckill_id,user_phone,state) VALUES (#{seckillId},#{userPhone},0) </insert> <select id="queryByIdWithSeckill" resultType="SuccessKilled"> <!--根據seckillId查詢SuccessKilled對象,並攜帶Seckill對象--> <!--如何告訴mybatis把結果映射到SuccessKill屬性同時映射到Seckill屬性--> <!--能夠自由控制SQL語句--> SELECT sk.seckill_id, sk.user_phone, sk.create_time, sk.state, s.seckill_id as "seckill.seckill_id", s.name "seckill.name", s.number "seckill.number", s.start_time "seckill.start_time", s.end_time "seckill.end_time", s.create_time "seckill.create_time" FROM success_killed sk INNER JOIN seckill s ON sk.seckill_id=s.seckill_id WHERE sk.seckill_id=#{seckillId} and sk.user_phone=#{userPhone} </select> </mapper>
完成了dao層開發,接下來對到dao方法進行測試。點擊咱們要測試的類,快捷鍵ctrl+shift+t,建立新的測試,選擇測試的路徑及所要測試的方法。
SeckillDaoTest.java
/** * Created by codingBoy on 16/11/27. * 配置spring和junit整合,這樣junit在啓動時就會加載springIOC容器 */ @RunWith(SpringJUnit4ClassRunner.class) //告訴junit spring的配置文件 @ContextConfiguration({"classpath:spring/spring-dao.xml"}) public class SeckillDaoTest { //注入Dao實現類依賴 @Resource private SeckillDao seckillDao; @Test public void reduceNumber() throws Exception { long seckillId=10000; Date date=new Date(); int updateCount=seckillDao.reduceNumber(seckillId,date); System.out.println(updateCount); } @Test public void queryById() throws Exception { long seckillId=10000; Seckill seckill=seckillDao.queryById(seckillId); System.out.println(seckill.getName()); System.out.println(seckill); } @Test public void queryAll() throws Exception { List<Seckill> seckills=seckillDao.queryAll(0,100); for (Seckill seckill : seckills) { System.out.println(seckill); } } @Test public void addItem() throws Exception { Seckill seckill = new Seckill("222",300,new Date(),new Date()); seckillDao.addItem(seckill); } @Test public void deleteById() throws Exception { seckillDao.deleteById(10011); } @Test public void updateItem() throws Exception { Seckill seckill = seckillDao.queryById(10018); seckill.setNumber(500); seckillDao.updateItem(seckill); } }
dao層開發過程當中的注意點
對全部的dao包中的方法進行測試後,就可進入service層方法的開發。
service層爲主要的業務邏輯層,也是最複雜的部分,通常在service下新建一個接口,而後在impl包下放接口的實現類。
SeckillService.java
/**業務接口:站在使用者(程序員)的角度設計接口 * 三個方面:1.方法定義粒度,方法定義的要很是清楚2.參數,要越簡練越好 * 3.返回類型(return 類型必定要友好/或者return異常,咱們容許的異常) * Created by codingBoy on 16/11/27. */ public interface SeckillService { /** * 查詢所有的秒殺記錄 * @return */ List<Seckill> getSeckillList(); /** *查詢單個秒殺記錄 * @param seckillId * @return */ Seckill getById(long seckillId); //再往下,是咱們最重要的行爲的一些接口 /** * 在秒殺開啓時輸出秒殺接口的地址,不然輸出系統時間和秒殺時間 * @param seckillId */ Exposer exportSeckillUrl(long seckillId); /** * 執行秒殺操做,有可能失敗,有可能成功,因此要拋出咱們容許的異常 * @param seckillId * @param userPhone * @param md5 * @return */ SeckillExecution executeSeckill(long seckillId, long userPhone, String md5) throws SeckillException,RepeatKillException,SeckillCloseException; void addItem(Seckill seckill); void deleteItemById(long seckillId); void updateItemById(Seckill seckill); }
SeckillServiceImpl.java
@Service public class SeckillServiceImpl implements SeckillService { //日誌對象 private Logger logger= LoggerFactory.getLogger(this.getClass()); //加入一個混淆字符串(秒殺接口)的salt,爲了我避免用戶猜出咱們的md5值,值任意給,越複雜越好 private final String salt="shsdssljdd'l."; //注入Service依賴 @Autowired //@Resource private SeckillDao seckillDao; @Autowired //@Resource private SuccessKilledDao successKilledDao; public List<Seckill> getSeckillList() { return seckillDao.queryAll(0,100); } public Seckill getById(long seckillId) { return seckillDao.queryById(seckillId); } 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 (startTime.getTime()>nowTime.getTime() || endTime.getTime()<nowTime.getTime()) { return new Exposer(false,seckillId,nowTime.getTime(),startTime.getTime(),endTime.getTime()); } //秒殺開啓,返回秒殺商品的id、用給接口加密的md5 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; } //秒殺是否成功,成功:減庫存,增長明細;失敗:拋出異常,事務回滾 @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{ //不然更新了庫存,秒殺成功,增長明細 int insertCount=successKilledDao.insertSuccessKilled(seckillId,userPhone); //看是否該明細被重複插入,即用戶是否重複秒殺 if (insertCount<=0) { throw new RepeatKillException("seckill repeated"); }else { //減庫存,熱點商品競爭 int updateCount=seckillDao.reduceNumber(seckillId,nowTime); if (updateCount<=0) { //沒有更新庫存記錄,說明秒殺結束 rollback throw new SeckillCloseException("seckill is closed"); }else { //秒殺成功,獲得成功插入的明細記錄,並返回成功秒殺的信息 commit SuccessKilled successKilled=successKilledDao.queryByIdWithSeckill(seckillId,userPhone); return new SeckillExecution(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 void addItem(Seckill seckill) { seckillDao.addItem(seckill); } public void deleteItemById(long seckillId) { seckillDao.deleteById(seckillId); } public void updateItemById(Seckill seckill) { seckillDao.updateItem(seckill); } }
以上代碼中用到了dto、enums、exception包中自定義的類。
dto包下三個類
//省略getter,setter和toString方法 public class Exposer { //是否開啓秒殺 private boolean exposed; //加密措施 private String md5; 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; } }
//省略getter,setter和toString方法 public class SeckillExecution { private long seckillId; //秒殺執行結果的狀態 private int state; //狀態的明文標識 private String stateInfo; //當秒殺成功時,須要傳遞秒殺成功的對象回去 private SuccessKilled successKilled; //秒殺成功返回全部信息 public SeckillExecution(long seckillId, SeckillStatEnum statEnum, SuccessKilled successKilled) { this.seckillId = seckillId; this.state = statEnum.getState(); this.stateInfo = statEnum.getInfo(); this.successKilled = successKilled; } //秒殺失敗 public SeckillExecution(long seckillId, SeckillStatEnum statEnum) { this.seckillId = seckillId; this.state = statEnum.getState(); this.stateInfo = statEnum.getInfo(); } }
//將全部的ajax請求返回類型,所有封裝成json數據 public class SeckillResult<T> { //請求是否成功 private boolean success; private T data; private String error; public SeckillResult(boolean success, T data) { this.success = success; this.data = data; } public SeckillResult(boolean success, String error) { this.success = success; this.error = error; } }
新建enums存放枚舉類型
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; } }
新建exception存放自定義的異常類
public class RepeatKillException extends SeckillException { public RepeatKillException(String message) { super(message); } public RepeatKillException(String message, Throwable cause) { super(message, cause); } }
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); } }
完成service層,進行測試
控制層開發
在web包下新建控制類
SeckillController.java
/* * /seckill/list 獲取列表 * /seckill/{seckillId}/detail 物品詳情 * /seckill/{seckillId}/exposer 獲取物品秒殺地址 * /seckill/{seckillId}/{md5}/execution 執行物品秒殺 * * /seckill/add get獲取添加頁面 * /seckill/add post向數據庫中添加記錄 * /seckill/{seckillId}/update get獲取更新頁面 * /seckill/update post更新數據 * /seckill//{seckillId}delete 刪除數據 * */ @Controller @RequestMapping("/seckill")//url:模塊/資源/{}/細分 public class SeckillController { @Autowired private SeckillService seckillService; @RequestMapping(value = "/list",method = RequestMethod.GET) public String list(Model model) { //list.jsp+mode=ModelAndView //獲取列表頁 List<Seckill> list=seckillService.getSeckillList(); model.addAttribute("list",list); return "list"; } @RequestMapping(value = "/{seckillId}/detail",method = RequestMethod.GET) public String detail(@PathVariable("seckillId") Long seckillId, Model model) { if (seckillId == null) { return "redirect:/seckill/list"; } Seckill seckill=seckillService.getById(seckillId); if (seckill==null) { return "forward:/seckill/list"; } model.addAttribute("seckill",seckill); return "detail"; } @RequestMapping(value = "/add",method = {RequestMethod.GET}) public String addItemUI(){ return "add"; } @RequestMapping(value = "/add",method = {RequestMethod.POST}) public String addItemInfo(Seckill seckill){ seckillService.addItem(seckill); return "redirect:/seckill/list"; } @RequestMapping(value = "/{sk.seckillId}/delete",method = {RequestMethod.GET}) public String deleteItem(@PathVariable("sk.seckillId") Long seckillId){ seckillService.deleteItemById(seckillId); return "redirect:/seckill/list"; } @RequestMapping(value = "/{sk.seckillId}/update",method = {RequestMethod.GET}) public String updateItemUI(@PathVariable("sk.seckillId") Long seckillId,Model model){ Seckill seckill = seckillService.getById(seckillId); model.addAttribute("item",seckill); return "update"; } @RequestMapping(value = "/update",method = {RequestMethod.POST}) public String updateItem(Seckill seckill){ seckillService.updateItemById(seckill); return "redirect:/seckill/list"; } //ajax ,json暴露秒殺接口的方法 @RequestMapping(value = "/{seckillId}/exposer", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"}) @ResponseBody public SeckillResult<Exposer> exposer(@PathVariable("seckillId") Long seckillId) { SeckillResult<Exposer> result; try{ Exposer exposer=seckillService.exportSeckillUrl(seckillId); result=new SeckillResult<Exposer>(true,exposer); }catch (Exception e) { e.printStackTrace(); result=new SeckillResult<Exposer>(false,e.getMessage()); } return result; } @RequestMapping(value = "/{seckillId}/{md5}/execution", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) @ResponseBody public SeckillResult<SeckillExecution> execute(@PathVariable("seckillId") Long seckillId, @PathVariable("md5") String md5, @CookieValue(value = "userPhone",required = false) Long userPhone) { if (userPhone==null) { return new SeckillResult<SeckillExecution>(false,"未註冊"); } SeckillResult<SeckillExecution> result; try { SeckillExecution execution = seckillService.executeSeckill(seckillId, userPhone, md5); return new SeckillResult<SeckillExecution>(true, execution); }catch (RepeatKillException e1) { SeckillExecution execution=new SeckillExecution(seckillId, SeckillStatEnum.REPEAT_KILL); return new SeckillResult<SeckillExecution>(true,execution); }catch (SeckillCloseException e2) { SeckillExecution execution=new SeckillExecution(seckillId, SeckillStatEnum.END); return new SeckillResult<SeckillExecution>(true,execution); } catch (Exception e) { SeckillExecution execution=new SeckillExecution(seckillId, SeckillStatEnum.INNER_ERROR); return new SeckillResult<SeckillExecution>(true,execution); } } //獲取系統時間 @RequestMapping(value = "/time/now",method = RequestMethod.GET) @ResponseBody public SeckillResult<Long> time() { Date now=new Date(); return new SeckillResult<Long>(true,now.getTime()); } }
web層開發過程當中的注意點
目前爲止,秒殺系統後端服務所有完成,前端相關代碼就不在此貼出來,所有代碼見github