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

本篇文章總結(jié)自己開發(fā)秒殺系統(tǒng)Web層的過程,主要介紹前端交互設(shè)計(jì)、Restful:url滿足Restful設(shè)計(jì)規(guī)范、Spring MVC、bootstrap+jquery這四個(gè)方面的開發(fā)。

1.前端交互流程設(shè)計(jì)

對(duì)于一個(gè)系統(tǒng),需要產(chǎn)品經(jīng)理、前端工程師和后端工程師的參數(shù),產(chǎn)品經(jīng)理將用戶的需求做成一個(gè)開發(fā)文檔交給前端工程師和后端工程師,前端工程師為系統(tǒng)完成頁(yè)面的開發(fā),后端工程師為系統(tǒng)完成業(yè)務(wù)邏輯的開發(fā)。對(duì)于我們這個(gè)秒殺系統(tǒng),它的前端交互流程設(shè)計(jì)如下圖:

這個(gè)流程圖就告訴了我們?cè)斍轫?yè)的流程邏輯,前端工程師根據(jù)這個(gè)流程圖設(shè)計(jì)頁(yè)面,而我們后端工程師根據(jù)這個(gè)流程圖開發(fā)我們對(duì)應(yīng)的代碼。前端交互流程是系統(tǒng)開發(fā)中很重要的一部分,接下來進(jìn)行Restful接口設(shè)計(jì)的學(xué)習(xí)。

2.Restful接口設(shè)計(jì)學(xué)習(xí)

什么是Restful?它就是一種優(yōu)雅的URI表述方式,用來設(shè)計(jì)我們資源的訪問URL。通過這個(gè)URL的設(shè)計(jì),我們就可以很自然的感知到這個(gè)URL代表的是哪種業(yè)務(wù)場(chǎng)景或者什么樣的數(shù)據(jù)或資源?;赗estful設(shè)計(jì)的URL,對(duì)于我們接口的使用者、前端、web系統(tǒng)或者搜索引擎甚至是我們的用戶,都是非常友好的。關(guān)于Restful的了解大家去網(wǎng)上一搜一大把,我這里就不再做介紹了。下面看看我們這個(gè)秒殺系統(tǒng)的URL設(shè)計(jì):

接下來基于上述資源接口來開始我們對(duì)Spring MVC框架的使用。

3.整合配置Spring MVC框架

首先在WEB-INF的web.xml中進(jìn)行我們前端控制器DispatcherServlet的配置,如下:

<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.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>
        <!--默認(rèn)匹配所有請(qǐng)求-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

然后在spring容器中進(jìn)行web層相關(guān)bean(即Controller)的配置,在spring包下創(chuàng)建一個(gè)spring-web.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"
       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.自動(dòng)注冊(cè)DefaultAnnotationHandlerMapping,AnnotationMethodHandlerAdapter
    b.默認(rèn)提供一系列的功能:數(shù)據(jù)綁定,數(shù)字和日期的format@NumberFormat,@DateTimeFormat
    c:xml,json的默認(rèn)讀寫支持-->
    <mvc:annotation-driven/>

    <!--2.靜態(tài)資源默認(rèn)servlet配置-->
    <!--
        1).加入對(duì)靜態(tài)資源處理: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相關(guān)的bean-->
    <context:component-scan base-package="cn.codingxiaxw.web"/>
</beans>

這樣我們便完成了Spring MVC的相關(guān)配置(即將Spring MVC框架整合到了我們的項(xiàng)目中),接下來就要基于Restful接口進(jìn)行我們項(xiàng)目的Controller開發(fā)工作了。

4.Controller開發(fā)

Controller中的每一個(gè)方法都對(duì)應(yīng)我們系統(tǒng)中的一個(gè)資源URL,其設(shè)計(jì)應(yīng)該遵循Restful接口的設(shè)計(jì)風(fēng)格。在cn.codingxiaxw包下創(chuàng)建一個(gè)web包用于放web層Controller開發(fā)的代碼,在該包下創(chuàng)建一個(gè)SeckillController.java,內(nèi)容如下:

@Component
@RequestMapping("/seckill")//url:模塊/資源/{}/細(xì)分
public class SeckillController
{
    @Autowired
    private SeckillService seckillService;

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String list(Model model)
    {
        //list.jsp+mode=ModelAndView
        //獲取列表頁(yè)
        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";
    }

    //ajax ,json暴露秒殺接口的方法
    @RequestMapping(value = "/{seckillId}/exposer",
                    method = RequestMethod.POST,
                    produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public SeckillResult<Exposer> exposer(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 = "killPhone",required = false) Long phone)
    {
        if (phone==null)
        {
            return new SeckillResult<SeckillExecution>(false,"未注冊(cè)");
        }
        SeckillResult<SeckillExecution> result;

        try {
            SeckillExecution execution = seckillService.executeSeckill(seckillId, phone, md5);
            return new SeckillResult<SeckillExecution>(true, execution);
        }catch (RepeatKillException e1)
        {
            SeckillExecution execution=new SeckillExecution(seckillId, SeckillStatEnum.REPEAT_KILL);
            return new SeckillResult<SeckillExecution>(false,execution);
        }catch (SeckillCloseException e2)
        {
            SeckillExecution execution=new SeckillExecution(seckillId, SeckillStatEnum.END);
            return new SeckillResult<SeckillExecution>(false,execution);
        }
        catch (Exception e)
        {
            SeckillExecution execution=new SeckillExecution(seckillId, SeckillStatEnum.INNER_ERROR);
            return new SeckillResult<SeckillExecution>(false,execution);
        }

    }

    //獲取系統(tǒng)時(shí)間
    @RequestMapping(value = "/time/now",method = RequestMethod.GET)
    public SeckillResult<Long> time()
    {
        Date now=new Date();
        return new SeckillResult<Long>(true,now.getTime());
    }
}

Controller開發(fā)中的方法完全是對(duì)照Service接口方法進(jìn)行開發(fā)的,第一個(gè)方法用于訪問我們商品的列表頁(yè),第二個(gè)方法訪問商品的詳情頁(yè),第三個(gè)方法用于返回一個(gè)json數(shù)據(jù),數(shù)據(jù)中封裝了我們商品的秒殺地址,第四個(gè)方法用于封裝用戶是否秒殺成功的信息,第五個(gè)方法用于返回系統(tǒng)當(dāng)前時(shí)間。代碼中涉及到一個(gè)將返回秒殺商品地址封裝為json數(shù)據(jù)的一個(gè)Vo類,即SeckillResult.java,在dto包中創(chuàng)建它,內(nèi)容如下:

//將所有的ajax請(qǐng)求返回類型,全部封裝成json數(shù)據(jù)
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;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }
}

到此,Controller的開發(fā)任務(wù)完成,接下來進(jìn)行我們的頁(yè)面開發(fā)。

5.頁(yè)面開發(fā)

頁(yè)面由前端工程師完成,這里直接拷貝我github上源代碼中jsp的代碼(webapp包下的所有資源)即可。

然后運(yùn)行Tomcat服務(wù)器,在瀏覽器中輸入http://localhost:8080/seckill/list,即可訪問我們的秒殺列表頁(yè)面:

點(diǎn)擊相應(yīng)商品后面的詳情頁(yè)鏈接即可查看該商品是否開啟秒殺、秒殺該商品等活動(dòng)。到此,web層的開發(fā)也結(jié)束,我們的系統(tǒng)開發(fā)便告一段落。但往往這樣一個(gè)秒殺系統(tǒng),往往是會(huì)有成千上萬(wàn)的人進(jìn)行參與,我們目前的系統(tǒng)是抗不起多少高并發(fā)操作的,所以后面我們會(huì)對(duì)本系統(tǒng)進(jìn)行高并發(fā)的優(yōu)化。請(qǐng)查看我的下篇文章Java高并發(fā)秒殺API之高并發(fā)優(yōu)化(待更新)

6.聯(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),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 之前寫了一個(gè)用SSM框架搭建的商品查詢系統(tǒng),分兩篇文章分別記錄了自己整合SSM框架的過程以及利用SSM開發(fā)的一些基...
    codingXiaxw閱讀 5,167評(píng)論 7 29
  • 源碼:https://github.com/joshul/seckill 本篇文章總結(jié)自己開發(fā)秒殺系統(tǒng)Web層的過...
    joshul閱讀 784評(píng)論 1 0
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,953評(píng)論 6 342
  • 我們平常比較常用的模型緩存一般都是通過歸檔解檔實(shí)現(xiàn)的,詳情請(qǐng)參考我之前寫的一篇文章歸檔解檔。今天我介紹的一種新的緩...
    海到盡頭天為岸閱讀 1,123評(píng)論 1 0
  • 最近聽了不少別人的分享以及看了不少電影,也做了一些整理,以及寫了一些相關(guān)的評(píng)論。有些是根據(jù)分享寫的逐字稿,所以前后...
    金禪子閱讀 526評(píng)論 0 0