Java高并發秒殺API之web層

源碼:https://github.com/joshul/seckill

本篇文章總結自己開發秒殺系統Web層的過程,主要介紹前端交互設計、Restful:url滿足Restful設計規范、Spring MVC、bootstrap+jquery這四個方面的開發。

1.前端交互流程設計

對于一個系統,需要產品經理、前端工程師和后端工程師的參數,產品經理將用戶的需求做成一個開發文檔交給前端工程師和后端工程師,前端工程師為系統完成頁面的開發,后端工程師為系統完成業務邏輯的開發。對于我們這個秒殺系統,它的前端交互流程設計如下圖:

Paste_Image.png

這個流程圖就告訴了我們詳情頁的流程邏輯,前端工程師根據這個流程圖設計頁面,而我們后端工程師根據這個流程圖開發我們對應的代碼。前端交互流程是系統開發中很重要的一部分,接下來進行Restful接口設計的學習。
設計學習)

2.Restful接口設計學習

什么是Restful?它就是一種優雅的URI表述方式,用來設計我們資源的訪問URL。通過這個URL的設計,我們就可以很自然的感知到這個URL代表的是哪種業務場景或者什么樣的數據或資源。基于Restful設計的URL,對于我們接口的使用者、前端、web系統或者搜索引擎甚至是我們的用戶,都是非常友好的。關于Restful的了解大家去網上一搜一大把,我這里就不再做介紹了。下面看看我們這個秒殺系統的URL設計:

Paste_Image.png

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

3.整合配置Spring MVC框架

首先在WEB-INF的web.xml中進行我們前端控制器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創建的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>
</web-app>

然后在spring容器中進行web層相關bean(即Controller)的配置,在spring包下創建一個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相關的bean-->
    <context:component-scan base-package="cn.codingxiaxw.web"/>
</beans>

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

4.Controller開發

Controller中的每一個方法都對應我們系統中的一個資源URL,其設計應該遵循Restful接口的設計風格。在org.seckill包下創建一個web包用于放web層Controller開發的代碼,在該包下創建一個SeckillController.java,內容如下:

@Component
@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";
    }

    //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,"未注冊");
        }
        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);
        }

    }

    //獲取系統時間
    @RequestMapping(value = "/time/now",method = RequestMethod.GET)
    public SeckillResult<Long> time()
    {
        Date now=new Date();
        return new SeckillResult<Long>(true,now.getTime());
    }
}
Controller開發中的方法完全是對照Service接口方法進行開發的,第一個方法用于訪問我們商品的列表頁,第二個方法訪問商品的詳情頁,第三個方法用于返回一個json數據,數據中封裝了我們商品的秒殺地址,第四個方法用于封裝用戶是否秒殺成功的信息,第五個方法用于返回系統當前時間。代碼中涉及到一個將返回秒殺商品地址封裝為json數據的一個Vo類,即SeckillResult.java,在dto包中創建它,內容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//將所有的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;
    }

    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的開發任務完成,接下來進行我們的頁面開發。
5.頁面開發
頁面由前端工程師完成,這里直接拷貝我github上源代碼中jsp的代碼(webapp包下的所有資源)即可。
點擊相應商品后面的詳情頁鏈接即可查看該商品是否開啟秒殺、秒殺該商品等活動。到此,web層的開發也結束,我們的系統開發便告一段落。但往往這樣一個秒殺系統,往往是會有成千上萬的人進行參與,我們目前的系統是抗不起多少高并發操作的,所以后面我們會對本系統進行高并發的優化。請查看我的下篇文章Java高并發秒殺API之高并發優化(待更新)

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容