Java高并發(fā)秒殺系統(tǒng)API(一)之DAO層開發(fā)

之前寫了一個(gè)用SSM框架搭建的商品查詢系統(tǒng),分兩篇文章分別記錄了自己整合SSM框架的過程以及利用SSM開發(fā)的一些基礎(chǔ)知識(shí),由于那時(shí)候剛學(xué)完SSM框架,所以自己覺得整合的過程總結(jié)的不夠好。如今在有了一定的SSM框架開發(fā)經(jīng)驗(yàn)后打算參考相應(yīng)的資料再寫一個(gè)用Maven+SSM做的一個(gè)秒殺系統(tǒng),從頭到位記錄自己整合SSM框架以及用SSM框架開發(fā)這個(gè)秒殺系統(tǒng)的過程。

為什么要用maven?這個(gè)工具真是讓你用了以后就愛不釋手。這樣給你簡單的說說maven,它的強(qiáng)大之處就是你不用再像以前那樣,如果在項(xiàng)目中用到spring框架還要到spring官網(wǎng)上去下載一系列的jar包,用了maven對(duì)項(xiàng)目進(jìn)行管理之后你就可以直接在它的pom.xml文件中添加jar包的相應(yīng)坐標(biāo),這樣maven就能自動(dòng)從它的中央倉庫中為我們將這些jar包下載到其本地倉庫中供我們使用。

用maven對(duì)項(xiàng)目進(jìn)行管理的知識(shí)很簡單,關(guān)于創(chuàng)建maven項(xiàng)目的知識(shí)大家看我的這篇文章便可以在幾分鐘內(nèi)掌握:Maven安裝配置及創(chuàng)建你的第一個(gè)Maven項(xiàng)目

秒殺系統(tǒng)搭建環(huán)境:IDEA+Maven+SSM框架。源碼請(qǐng)點(diǎn)擊這里前往我的github。

完成這個(gè)秒殺系統(tǒng),需要完成四個(gè)模塊的代碼編寫,分別是:

其實(shí)完成這三個(gè)模塊就可以完成我們的秒殺系統(tǒng)了,但對(duì)于我們的秒殺系統(tǒng)中一件秒殺商品,在秒殺的時(shí)候肯定會(huì)有成千上萬的用戶參與進(jìn)來,通過上述三個(gè)模塊完成的系統(tǒng)無法解決這么多用戶的高并發(fā)操作,所以我們還需要第四個(gè)模塊:

該系統(tǒng)我將按照上述4個(gè)模塊通過4篇文章來完成介紹,本篇文章進(jìn)行第一個(gè)模塊的講解及項(xiàng)目的介紹以及Dao層編碼的開發(fā)。首先看看我們項(xiàng)目的效果圖:

列表頁:

詳情頁:

接下來我將從如何用maven創(chuàng)建我們的秒殺系統(tǒng)seckill項(xiàng)目開始到完成我們的秒殺系統(tǒng),詳細(xì)介紹自己完成它的過程。

1.相關(guān)技術(shù)介紹

MySQL:1.這里我們采用手寫代碼創(chuàng)建相關(guān)表,掌握這種能力對(duì)我們以后的項(xiàng)目二次上線會(huì)有很大的幫助;2.SQL技巧;3.事務(wù)和行級(jí)鎖的理解和一些應(yīng)用。

MyBatis:1.DAO層的設(shè)計(jì)與開發(fā)。2.MyBatis的合理使用,使用Mapper動(dòng)態(tài)代理的方式進(jìn)行數(shù)據(jù)庫的訪問。3.MyBatis和Spring框架的整合:如何高效的去整合MyBatis和Spring框架。

Spring:1.Spring IOC幫我們整合Service以及Service所有的依賴。2.聲明式事務(wù)。對(duì)Spring聲明式事務(wù)做一些分析以及它的行為分析。

Spring MVC:1.Restful接口設(shè)計(jì)和使用。Restful現(xiàn)在更多的被應(yīng)用在一些互聯(lián)網(wǎng)公司W(wǎng)eb層接口的應(yīng)用上。2.框架運(yùn)作流程。3.Spring Controller的使用技巧。

前端:1.交互設(shè)計(jì)。2.bootstrap。3.JQuery。設(shè)計(jì)到前端的頁面代碼我們直接拷貝即可,畢竟真正開發(fā)中這樣一個(gè)項(xiàng)目是由產(chǎn)品經(jīng)理、前端工程師、后端工程師一起完成的。

高并發(fā):1.高并發(fā)點(diǎn)和高并發(fā)分析。2.優(yōu)化思路并實(shí)現(xiàn)。

下面開始我們的項(xiàng)目的開發(fā)。

2.Java高并發(fā)秒殺APi之業(yè)務(wù)分析與DAO層代碼編寫

2.1用Maven創(chuàng)建我們的項(xiàng)目seckill

在命令行中輸入如下命令:

mvn archetype:generate -DgroupId=cn.codingxiaxw.seckill -DartifactId=seckill -Dpackage=cn.codingxiaxw.seckill -Dversion=1.0-SNAPSHOT -DarchetypeArtifactId=maven-archetype-webapp

然后使用IDEA打開該項(xiàng)目,在IDEA中對(duì)項(xiàng)目按照Maven項(xiàng)目的標(biāo)準(zhǔn)骨架補(bǔ)全我們項(xiàng)目的相應(yīng)文件包,最后的工程結(jié)構(gòu)如下:

main包下進(jìn)行我們項(xiàng)目的代碼編寫及相關(guān)配置文件,test包下進(jìn)行我們項(xiàng)目的測(cè)試。

打開WEB-INF下的web.xml,它默認(rèn)為我們創(chuàng)建servlet版本為2.3,需要修改它的根標(biāo)簽為:

<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創(chuàng)建的web-app需要修改servlet的版本為3.0-->


</web-app>

然后打開pom.xml,在里面添加我們需要的第三方j(luò)ar包的坐標(biāo)配置信息,如SSM框架、數(shù)據(jù)庫、日志,如下:

<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>cn.codingxiaxw.seckill</groupId>
  <artifactId>seckill</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>seckill Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <!--3.0的junit是使用編程的方式來進(jìn)行測(cè)試,而junit4是使用注解的方式來運(yùn)行junit-->
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>


    <!--補(bǔ)全項(xiàng)目依賴-->
    <!--1.日志 java日志有:slf4j,log4j,logback,common-logging
        slf4j:是規(guī)范/接口
        日志實(shí)現(xiàn):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>
    <!--實(shí)現(xiàn)slf4j接口并整合-->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.1.1</version>
    </dependency>


    <!--1.數(shù)據(jù)庫相關(guān)依賴-->
    <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.1</version>
    </dependency>

    <!--2.dao框架:MyBatis依賴-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.0</version>
    </dependency>
    <!--mybatis自身實(shí)現(xiàn)的spring整合依賴-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.3</version>
    </dependency>

    <!--3.Servlet web相關(guān)依賴-->
    <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相關(guān)依賴-->
    <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相關(guān)依賴-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.1.7.RELEASE</version>
    </dependency>

  </dependencies>

  <build>
    <finalName>seckill</finalName>
  </build>
</project>

到此,我們項(xiàng)目的初始化工作完成。

2.2秒殺系統(tǒng)業(yè)務(wù)分析

秒殺系統(tǒng)業(yè)務(wù)流程如下:

由圖可以發(fā)現(xiàn),整個(gè)系統(tǒng)其實(shí)是針對(duì)庫存做的系統(tǒng)。用戶成功秒殺商品,對(duì)于我們系統(tǒng)的操作就是:1.減庫存。2.記錄用戶的購買明細(xì)。下面看看我們用戶對(duì)庫存的業(yè)務(wù)分析:

記錄用戶的秒殺成功信息,我們需要記錄:1.誰購買成功了。2.購買成功的時(shí)間/有效期。3.付款/發(fā)貨信息。這些數(shù)據(jù)組成了用戶的秒殺成功信息,也就是用戶的購買行為。

為什么我們的系統(tǒng)需要事務(wù)?看如下這些故障:1.若是用戶成功秒殺商品我們記錄了其購買明細(xì)卻沒有減庫存。導(dǎo)致商品的超賣。2.減了庫存卻沒有記錄用戶的購買明細(xì)。導(dǎo)致商品的少賣。對(duì)于上述兩個(gè)故障,若是沒有事務(wù)的支持,損失最大的無疑是我們的用戶和商家。在MySQL中,它內(nèi)置的事務(wù)機(jī)制,可以準(zhǔn)確的幫我們完成減庫存和記錄用戶購買明細(xì)的過程。

MySQL實(shí)現(xiàn)秒殺的難點(diǎn)分析:當(dāng)用戶A秒殺id為10的商品時(shí),此時(shí)MySQL需要進(jìn)行的操作是:1.開啟事務(wù)。2.更新商品的庫存信息。3.添加用戶的購買明細(xì),包括用戶秒殺的商品id以及唯一標(biāo)識(shí)用戶身份的信息如電話號(hào)碼等。4.提交事務(wù)。若此時(shí)有另一個(gè)用戶B也在秒殺這件id為10的商品,他就需要等待,等待到用戶A成功秒殺到這件商品然后MySQL成功的提交了事務(wù)他才能拿到這個(gè)id為10的商品的鎖從而進(jìn)行秒殺,而同一時(shí)間是不可能只有用戶B在等待,肯定是有很多很多的用戶都在等待拿到這個(gè)行級(jí)鎖。秒殺的難點(diǎn)就在這里,如何高效的處理這些競(jìng)爭(zhēng)?如何高效的完成事務(wù)?在后面第4個(gè)模塊如何進(jìn)行高并發(fā)的優(yōu)化為大家講解。

我們這個(gè)系統(tǒng)需要完成秒殺的哪些功能?先來看看天貓的一個(gè)秒殺庫存系統(tǒng):

大家看了是不是覺得很復(fù)雜?當(dāng)然不用擔(dān)心,我們只是實(shí)現(xiàn)秒殺的一些功能:1.秒殺接口的暴露。2.執(zhí)行秒殺的操作。3.相關(guān)查詢,比如說列表查詢,詳情頁查詢。我們實(shí)現(xiàn)這三個(gè)功能即可。接下來進(jìn)行具體的編碼工作,首先是Dao層的編碼。

2.3Dao層設(shè)計(jì)開發(fā)

首先創(chuàng)建數(shù)據(jù)庫,相關(guān)表的sql語句我在main包下的sql包中已經(jīng)給出。

然后創(chuàng)建對(duì)應(yīng)表的實(shí)體類,在java包下創(chuàng)建cn.codingxiaxw.entity包,創(chuàng)建一個(gè)Seckill.java實(shí)體類,代碼如下:

public class Seckill
{
    private long seckillId;
    private String name;
    private int number;
    private Date startTime;
    private Date endTime;
    private Date createTime;

    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 +
                '}';
    }
}

和一個(gè)SuccessKilled.java,代碼如下:

public class SuccessKilled
{
    private long seckillId;
    private long userPhone;
    private short state;
    private Date createTime;

    //多對(duì)一,因?yàn)橐患唐吩趲齑嬷杏泻芏鄶?shù)量,對(duì)應(yīng)的購買明細(xì)也有很多。
    private Seckill seckill;

    public long getSeckillId() {
        return seckillId;
    }

    public void setSeckillId(long seckillId) {
        this.seckillId = seckillId;
    }

    public long getUserPhone() {
        return userPhone;
    }

    public void setUserPhone(long userPhone) {
        this.userPhone = userPhone;
    }

    public short getState() {
        return state;
    }

    public void setState(short state) {
        this.state = state;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Seckill getSeckill() {
        return seckill;
    }

    public void setSeckill(Seckill seckill) {
        this.seckill = seckill;
    }

    @Override
    public String toString() {
        return "SuccessKilled{" +
                "seckillId=" + seckillId +
                ", userPhone=" + userPhone +
                ", state=" + state +
                ", createTime=" + createTime +
                '}';
    }
}

然后針對(duì)實(shí)體創(chuàng)建出對(duì)應(yīng)dao層的接口,在cn.codingxiaxw.dao包下創(chuàng)建Seckill.java:

public interface SeckillDao
{

    /**
     * 減庫存
     * @param seckillId
     * @param killTime
     * @return 如果影響行數(shù)>1,表示更新庫存的記錄行數(shù)
     */
    int reduceNumber(long seckillId, Date killTime);

    /**
     * 根據(jù)id查詢秒殺的商品信息
     * @param seckillId
     * @return
     */
    Seckill queryById(long seckillId);

    /**
     * 根據(jù)偏移量查詢秒殺商品列表
     * @param off
     * @param limit
     * @return
     */
    List<Seckill> queryAll(int off,int limit);

}

和SuccessKilled.java:

public interface SuccessKilledDao {

    /**
     * 插入購買明細(xì),可過濾重復(fù)
     * @param seckillId
     * @param userPhone
     * @return插入的行數(shù)
     */
    int insertSuccessKilled(long seckillId,long userPhone);


    /**
     * 根據(jù)秒殺商品的id查詢明細(xì)SuccessKilled對(duì)象(該對(duì)象攜帶了Seckill秒殺產(chǎn)品對(duì)象)
     * @param seckillId
     * @return
     */
    SuccessKilled queryByIdWithSeckill(long seckillId,long userPhone);
}

接下來基于MyBatis來實(shí)現(xiàn)我們之前設(shè)計(jì)的Dao層接口。首先需要配置我們的MyBatis,在resources包下創(chuàng)建MyBatis全局配置文件mybatis-config.xml文件,在瀏覽器中輸入http://mybatis.github.io/mybatis-3/zh/index.html打開MyBatis的官網(wǎng)文檔,點(diǎn)擊左邊的"入門"欄框,找到mybatis全局配置文件,在這里有xml的一個(gè)規(guī)范,也就是它的一個(gè)xml約束,拷貝:

<?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">

到我們的項(xiàng)目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"/>
        <!--使用列別名替換列名  默認(rèn)值為true
        select name as title(實(shí)體中的屬性名是title) form table;
        開啟后mybatis會(huì)自動(dòng)幫我們把表中name的值賦到對(duì)應(yīng)實(shí)體的title屬性中
        -->
        <setting name="useColumnLabel" value="true"/>

        <!--開啟駝峰命名轉(zhuǎn)換Table:create_time到 Entity(createTime)-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

</configuration>

配置文件創(chuàng)建好后我們需要關(guān)注的是Dao接口該如何實(shí)現(xiàn),mybatis為我們提供了mapper動(dòng)態(tài)代理開發(fā)的方式為我們自動(dòng)實(shí)現(xiàn)Dao的接口。在mapper包下創(chuàng)建對(duì)應(yīng)Dao接口的xml映射文件,里面用于編寫我們操作數(shù)據(jù)庫的sql語句,SeckillDao.xml和SuccessKilledDao.xml。既然又是一個(gè)xml文件,我們肯定需要它的dtd文件,在官方文檔中,點(diǎn)擊左側(cè)"XML配置",在它的一些事例中,找到它的xml約束:

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

加入到兩個(gè)mapper映射xml文件中,然后對(duì)照Dao層方法編寫我們的映射文件內(nèi)容如下:

SeckillDao.xml:

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.codingxiaxw.dao.SeckillDao">
    <!--目的:為dao接口方法提供sql語句配置
    即針對(duì)dao接口中的方法編寫我們的sql語句-->


    <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>


</mapper>

SuccessKilledDao.xml:

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.codingxiaxw.dao.SuccessKilledDao">

    <insert id="insertSuccessKilled">
        <!--當(dāng)出現(xiàn)主鍵沖突時(shí)(即重復(fù)秒殺時(shí)),會(huì)報(bào)錯(cuò);不想讓程序報(bào)錯(cuò),加入ignore-->
        INSERT ignore INTO success_killed(seckill_id,user_phone,state)
        VALUES (#{seckillId},#{userPhone},0)
    </insert>

    <select id="queryByIdWithSeckill" resultType="SuccessKilled">

        <!--根據(jù)seckillId查詢SuccessKilled對(duì)象,并攜帶Seckill對(duì)象-->
        <!--如何告訴mybatis把結(jié)果映射到SuccessKill屬性同時(shí)映射到Seckill屬性-->
        <!--可以自由控制SQL語句-->
        SELECT
            sk.seckill_id,
            sk.user_phone,
            sk.create_time,
            sk.state,
            s.seckill_id "seckill.seckill_id",
            s.name "seckill.name",
            s.number "seckill",
            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>

接下來我們開始MyBatis和Spring的整合,整合目標(biāo):1.更少的編碼:只寫接口,不寫實(shí)現(xiàn)類。2.更少的配置:別名、配置掃描映射xml文件、dao實(shí)現(xiàn)。3.足夠的靈活性:自由定制SQL語句、自由傳結(jié)果集自動(dòng)賦值。

在resources包下創(chuàng)建一個(gè)spring包,里面放置spring對(duì)Dao、Service、transaction的配置文件。在瀏覽器中輸入http://docs.spring.io/spring/docs/進(jìn)入到Spring的官網(wǎng)中下載其pdf官方文檔,在其官方文檔中找到它的xml的定義內(nèi)容頭部:

<?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">

在spring包下創(chuàng)建一個(gè)spring配置dao層對(duì)象的配置文件spring-dao.xml,加入上述dtd約束,然后添加二者整合的配置,內(nèi)容如下:

<?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.配置數(shù)據(jù)庫相關(guān)參數(shù)-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--2.數(shù)據(jù)庫連接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--配置連接池屬性-->
        <property name="driverClass" value="${driver}" />

        <!-- 基本屬性 url、user、password -->
        <property name="jdbcUrl" value="${url}" />
        <property name="user" value="${username}" />
        <property name="password" value="${password}" />

        <!--c3p0私有屬性-->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <!--關(guān)閉連接后不自動(dòng)commit-->
        <property name="autoCommitOnClose" value="false"/>

        <!--獲取連接超時(shí)時(shí)間-->
        <property name="checkoutTimeout" value="1000"/>
        <!--當(dāng)獲取連接失敗重試次數(shù)-->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>

    <!--約定大于配置-->
    <!--3.配置SqlSessionFactory對(duì)象-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--往下才是mybatis和spring真正整合的配置-->
        <!--注入數(shù)據(jù)庫連接池-->
        <property name="dataSource" ref="dataSource"/>
        <!--配置mybatis全局配置文件:mybatis-config.xml-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--掃描entity包,使用別名,多個(gè)用;隔開-->
        <property name="typeAliasesPackage" value="cn.codingxiaxw.entity"/>
        <!--掃描sql配置文件:mapper需要的xml文件-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <!--4:配置掃描Dao接口包,動(dòng)態(tài)實(shí)現(xiàn)DAO接口,注入到spring容器-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--注入SqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 給出需要掃描的Dao接口-->
        <property name="basePackage" value="cn.codingxiaxw.dao"/>
    </bean>
</beans>

需要我們?cè)趓esources包下創(chuàng)建jdbc.properties用于配置數(shù)據(jù)庫的連接信息,內(nèi)容如下:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/seckill?useUnicode=true&characterEncoding=utf-8
username=root
password=xiaxunwu1996.

這樣我們便完成了Dao層編碼的開發(fā),接下來就可以利用junit進(jìn)行我們Dao層編碼的測(cè)試了。首先測(cè)試SeckillDao.java,利用IDEA快捷鍵shift+command+T對(duì)SeckillDao.java進(jìn)行測(cè)試,然后IDEA會(huì)自動(dòng)在test包的java包下為我們生成對(duì)SeckillDao.java中所有方法的測(cè)試類SeckillDaoTest.java,內(nèi)容如下:

public class SeckillDaoTest {
    @Test
    public void reduceNumber() throws Exception {

    }

    @Test
    public void queryById() throws Exception {

    }

    @Test
    public void queryAll() throws Exception {

    }
}

然后便可以在這個(gè)測(cè)試類中對(duì)SeckillDao接口的所有方法進(jìn)行測(cè)試了,先測(cè)試queryById()方法,在該方法中添加內(nèi)容:

/**
 * Created by codingBoy on 16/11/27.
 * 配置spring和junit整合,這樣junit在啟動(dòng)時(shí)就會(huì)加載spring容器
 */
@RunWith(SpringJUnit4ClassRunner.class)
//告訴junit spring的配置文件
@ContextConfiguration({"classpath:spring/spring-dao.xml"})
public class SeckillDaoTest {

    //注入Dao實(shí)現(xiàn)類依賴
    @Resource
    private SeckillDao seckillDao;


    @Test
    public void queryById() throws Exception {
        long seckillId=1000;
        Seckill seckill=seckillDao.queryById(seckillId);
        System.out.println(seckill.getName());
        System.out.println(seckill);
    }
}

右鍵選擇"debug queryById()",測(cè)試臺(tái)成功輸入該id為1000的商品信息,證明Dao的該方法正確,然后測(cè)試queryAll()方法,在該方法中添加如下內(nèi)容:

 @Test
    public void queryAll() throws Exception {

        List<Seckill> seckills=seckillDao.queryAll(0,100);
        for (Seckill seckill : seckills)
        {
            System.out.println(seckill);
        }
    }

然后運(yùn)行該方法,程序報(bào)錯(cuò),報(bào)錯(cuò)信息如下:

Caused by: org.apache.ibatis.binding.BindingException: Parameter 'offset' not found. Available parameters are [1, 0, param1, param2]

意思就是無法完成offset參數(shù)的綁定,這也是我們java編程語言的一個(gè)問題,也就是java沒有保存行參的記錄,java在運(yùn)行的時(shí)候會(huì)把List<Seckill> queryAll(int offset,int limit);中的參數(shù)變成這樣:queryAll(int arg0,int arg1),這樣我們就沒有辦法去傳遞多個(gè)參數(shù)。需要在SeckillDao接口中修改方法:

    List<Seckill> queryAll(@Param("offset") int offset,@Param("limit") int limit);

這樣才能使我們的MyBatis識(shí)別offset和limit兩個(gè)參數(shù),將Dao層方法中的這兩個(gè)參數(shù)與xml映射文件中sql語句的傳入?yún)?shù)完成映射。然后重新測(cè)試,發(fā)現(xiàn)測(cè)試通過。然后測(cè)試reduceNumber()方法,在該方法中加入如下內(nèi)容:

  @Test
    public void reduceNumber() throws Exception {

        long seckillId=1000;
        Date date=new Date();
        int updateCount=seckillDao.reduceNumber(seckillId,date);
        System.out.println(updateCount);

    }

運(yùn)行該方法,報(bào)錯(cuò):

Caused by: org.apache.ibatis.binding.BindingException: Parameter 'seckillId' not found. Available parameters are [1, 0, param1, param2]

發(fā)現(xiàn)依然是我們之前那個(gè)錯(cuò)誤,更改SeckillDao接口的reduceNumber()方法:

    int reduceNumber(@Param("seckillId") long seckillId, @Param("killTime") Date killTime);

然后重新運(yùn)行,測(cè)試通過,可是我們查詢數(shù)據(jù)庫發(fā)現(xiàn)該庫存表的商品數(shù)量沒有減少,是因?yàn)槲覀儺?dāng)前時(shí)間沒有達(dá)到秒殺商品要求的時(shí)間,所以不會(huì)成功秒殺。接下來進(jìn)行SuccessKilledDao接口相關(guān)方法的測(cè)試,依舊使用IDEA快捷鍵shift+command+T快速生成其方法的相應(yīng)測(cè)試類:

public class SuccessKilledDaoTest {
    @Test
    public void insertSuccessKilled() throws Exception  {

    }

    @Test
    public void queryByIdWithSeckill() throws Exception     {

    }
}

依然要在SuccessKilledDao的方法中用@Param注解完成參數(shù)的綁定,首先完成insertSuccessKilled()的測(cè)試:

@RunWith(SpringJUnit4ClassRunner.class)
//告訴junit spring的配置文件
@ContextConfiguration({"classpath:spring/spring-dao.xml"})
public class SuccessKilledDaoTest {

    @Resource
    private SuccessKilledDao successKilledDao;

    @Test
    public void insertSuccessKilled() throws Exception  {

        long seckillId=1000;
        long userPhone=13476191877L;
        int insertCount=successKilledDao.insertSuccessKilled(seckillId,userPhone);
        System.out.println("insertCount="+insertCount);
    }
}

運(yùn)行成功,測(cè)試臺(tái)打印出insertCount=1的信息,即我們修改了表中的一條記錄,這時(shí)查看秒殺成功明細(xì)表,發(fā)現(xiàn)該用戶的信息已經(jīng)被插入。然后再次運(yùn)行該測(cè)試方法,程序沒有報(bào)主鍵異常的錯(cuò),是因?yàn)槲覀冊(cè)诰帉懳覀兊拿骷?xì)表的時(shí)候添加了一個(gè)聯(lián)合主鍵的字段,它保證我們明細(xì)表中的seckillId和userPhone不能重復(fù)插入,另外在SuccessDao.xml中寫的插入語句的ignore關(guān)鍵字也保證了這點(diǎn)。控制臺(tái)輸出0,表示沒有對(duì)明細(xì)表做插入操作。然后進(jìn)行queryByIdWithSeckill()方法的測(cè)試,需要在Dao層的方法中添加@Param注解:

    SuccessKilled queryByIdWithSeckill(@Param("seckillId") long seckillId,@Param("userPhone") long userPhone);

然后進(jìn)行該方法的測(cè)試:

@Test
    public void queryByIdWithSeckill() throws Exception     {
        long seckillId=1000L;
        long userPhone=13476191877L;
        SuccessKilled successKilled=successKilledDao.queryByIdWithSeckill(seckillId,userPhone);
        System.out.println(successKilled);
        System.out.println(successKilled.getSeckill());


    }

運(yùn)行,成功查詢出我們明細(xì)表中id為1000且手機(jī)號(hào)碼為13476191877的用戶信息,并將表中對(duì)應(yīng)的信息映射到SuccessKilled對(duì)象和Seckill對(duì)象的屬性中。

到此,我們成功完成了Dao層開發(fā)及測(cè)試,接下來我們將進(jìn)行Service層的開發(fā)工作,請(qǐng)查看我的下篇文章Java高并發(fā)秒殺API之Service層開發(fā)

3.聯(lián)系

If you have some questions after you see this article,you can tell your doubts in the comments area or you can find some info by clicking these links.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 前言 本篇將完成DAO層的設(shè)計(jì)與開發(fā),包括: 數(shù)據(jù)庫、DAO實(shí)體與接口設(shè)計(jì)與編碼 基于MyBatis實(shí)現(xiàn)DAO編程...
    MOVE1925閱讀 1,383評(píng)論 0 4
  • 1.用Maven創(chuàng)建我們的項(xiàng)目seckill 利用Maven去創(chuàng)建工程然后導(dǎo)入Idea中并完成相關(guān)配置,這里的注意...
    joshul閱讀 3,934評(píng)論 0 3
  • 一步一步的搭建JAVA WEB項(xiàng)目,采用Maven構(gòu)建,基于MYBatis+Spring+Spring MVC+B...
    葉子的翅膀閱讀 12,725評(píng)論 5 25
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,991評(píng)論 19 139
  • “騷貨”這是自己的男人被別的女人引誘了,不敢管也管不了自己的男人,只好私下里稱呼男人的姘頭騷貨解解恨。蔑稱還有“蘇...
    南良大維閱讀 1,196評(píng)論 9 11