Service__kill of high concurrent second kill API

Source: Internet
Author: User

The last article describes the second kill DAO side will introduce the business logic code of the second kill. There is a unified control of the exception, the unified enumeration represents the state of the second kill, the second kill the business logic, Universal return. The
first defines an enumeration that represents the state of a second kill . Enumeration Definition

public enum Seckillstatenum {
    SUCCESS (1, "second kill successful"),
    end (0, "second Kill"),
    Repeat_kill (-1, "Repeat second Kill"),
    Inner_ KILL (-2, "System Exception"),
    Data_rewrite (-3, "data Tampering"),
    ;

    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;
    }
    private int state;
    Private String  Stateinfo;
    Private Seckillstatenum (int state, String stateinfo) {
        this.state = state;
        This.stateinfo = Stateinfo;
    }
    public static seckillstatenum stateinfo (int index) {for
        (Seckillstatenum state:values ()) {
            if ( State.getstate () ==index) {return state
                ;
            }
        }
        return null;
    }
}

The next set of three exceptions is to repeat the second kill exception, seconds to kill the exception, and seconds to kill the exception.
Two. Exception definition
1. Second Kill abnormal

public class Seckillexception extends runtimeexception{public
    seckillexception (String message) {
        Super ( message);
    }
    Public seckillexception (String message,throwable cause) {
        super (message,cause);
    }
}

2. Repeat second Kill exception

public class Repeatkillexception extends seckillexception{public
    repeatkillexception (String message) {
        Super (message);
    }
    Public repeatkillexception (String message,throwable cause) {
        super (message,cause);
    }
}

3. Second Kill end exception

public class Seckillcloseexception  extends seckillexception{public
    seckillcloseexception (String message) {
        super (message);
    }
    Public seckillcloseexception (String message,throwable cause) {
        super (message,cause);
    }
}
three. return value definition

This project requires two types of return, one is the second kill interface exposure, the other is the second kill result.
1. Second kill interface exposed return value

public class Exposer {//whether to open its second kill private Boolean exposed;
    Private String MD5;
    Private long seckillid;
    Current time private long now;
    Open time private long start;
    Ending time private long end;
        Public Exposer (Boolean exposed, String MD5, long Seckillid) {super ();
        this.exposed = exposed;
        THIS.MD5 = MD5;
    This.seckillid = Seckillid;
        Public Exposer (Boolean exposed, long Seckillid) {super ();
        this.exposed = exposed;
    This.seckillid = Seckillid;
        Public Exposer (Boolean exposed, long Seckillid,long now, long start, long end) {super ();
        this.exposed = exposed;
        This.now = Now;
        This.seckillid=seckillid;
        This.start = start;
    This.end = end;
    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 today) {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; }


}

2. Second kill result

public class Seckillexecution {private Long seckillid;
    Second kill status private int state;
    Private String Stateinfo;

    Private successkilled successkilled;
        Public Seckillexecution (Long seckillid, Seckillstatenum statenum) {super ();
        Seckillid = Seckillid;
        This.state = Statenum.getstate ();
    This.stateinfo = Statenum.getstateinfo ();
        Public Seckillexecution (Long seckillid, Seckillstatenum statenum, successkilled successkilled) {super ();
        Seckillid = Seckillid;
        This.state = Statenum.getstate ();
        This.stateinfo = Statenum.getstateinfo ();
    this.successkilled = successkilled;
    Public long Getseckillid () {return seckillid;
    } public void Setseckillid (long seckillid) {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; }

}
four. Second Kill service

1. Second kill service interface is mainly four methods, seconds kill list query, a single product information inquiries, seconds to kill address exposure, second kill execution.

Public interface Seckillservice {
    /**
     * Query all Seconds Kill Records
     * @return * 
     * * Public
    list<seckill> Getscekilllist ();
    /**
     * Inquiry delay Second Kill * * Public
    Seckill Getseckillbyid (long seckillid);
    /**
     * seconds kill excuse seconds to kill when the output address otherwise output system time and interface time
     * * Public
    exposer  exportseckillurl (long seckillid);
    /**
     * Execute second kill
    /seckillexecution  Executeseckill (Long Seckillid,long userphone, String MD5)
    Throws Seckillexception,repeatkillexception,seckillcloseexception;
}

2. Interface implementation

Package Com.wen.seckill.service.impl;
Import Java.util.Date;

Import java.util.List;

Import Javax.annotation.Resource;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import Org.springframework.stereotype.Service;
Import org.springframework.transaction.annotation.Transactional;

Import Org.springframework.util.DigestUtils;
Import Com.wen.seckill.dao.SeckillDao;
Import Com.wen.seckill.dao.SuccessKilledDao;
Import Com.wen.seckill.dto.Exposer;
Import com.wen.seckill.dto.SeckillExecution;
Import Com.wen.seckill.enums.SeckillStatEnum;
Import com.wen.seckill.exception.RepeatKillException;
Import com.wen.seckill.exception.SeckillCloseException;
Import com.wen.seckill.exception.SeckillException;
Import Com.wen.seckill.model.Seckill;
Import com.wen.seckill.model.SuccessKilled;
Import Com.wen.seckill.service.SeckillService; @Service ("Seckillservice") public class Seckillserviceimpl implements seckillservice{private Logger Logger = (Logger ) Loggerfactory.getlogger (seckillserviceiMpl.class);
    @Resource (name= "Seckilldao") private Seckilldao Seckilldao;
    @Resource (name= "Successkilleddao") private Successkilleddao Successkilleddao;
    Public final String slat= "Dfaf23asascxcaser23ads"; /** * Query all Seconds Kill records * @return/public list<seckill> getseckilllist () {return seckilldao.qu
    Eryall (); /** * Queries delay seconds kill/public Seckill Getseckillbyid (long seckillid) {return Seckilldao.querybyid (SE
    Ckillid); /** * seconds kill excuse seconds kill the output address otherwise output system time and interface time * * Public exposer Exportseckillurl (long seckillid) {Seckil
        L Seckill=seckilldao.querybyid (Seckillid);
        if (seckill==null) {return new exposer (false,seckillid);
            }else {Date starttime=seckill.getstarttime ();
            Date Endtime=seckill.getendtime ();
            Date Nowtime=new date (); if (Nowtime.gettime () <starttime.gettime () | |
           Nowtime.gettime () >endtime.gettime ()) {     return new Exposer (False,seckillid,nowtime.gettime (), Starttime.gettime (), Endtime.gettime ());
                }else {String md5=getmd5 (seckillid);
            return new Exposer (true,md5,seckillid); }}/** * Execute second Kill/@Transactional public seckillexecution Executeseckill (Long Seckil Lid,long Userphone, String MD5) throws seckillexception,repeatkillexception,seckillcloseexception{if (Md5==nul l| |!
        Md5.equals (GetMD5 (seckillid))) {throw new Seckillexception ("Seckill data Rewrite");
        //execute second Kill date Nowtime=new date ();
            try {int Updatecount=seckilldao.reducenumber (seckillid, nowtime);
                if (updatecount<=0) {//not updated DAO//throw new Seckillcloseexception ("Seckill ID closed");
            return new Seckillexecution (Seckillid,seckillstatenum.fail_kill); }else {//Reduce inventory success//Record purchase behavior int insertcount=successkilleddao.insertsuccesskilled (seckillid, Userphone); if (insertcount<=0) {//Repeat second kill//throw new Repeatkillexception ("Seckill ID repeate
                    D ");
                return new Seckillexecution (Seckillid,seckillstatenum.repeat_kill);
                    }else {successkilled Success=successkilleddao.querybyidwithseckill (seckillid, Userphone);
                return new Seckillexecution (seckillid,seckillstatenum.success,success);
            }}catch (Exception e) {e.printstacktrace ();
        throw new Seckillexception ("Seckill Inner Error" +e.getmessage ());
        } private String getMD5 (long seckillid) {string base=seckillid+ '/' +slat;
        String Md5=digestutils.md5digestashex (Base.getbytes ());
    return MD5;
 }
}

Due to the need to perform a reduction in inventory and insert a second kill record of the artificial need transactions here we use annotations to control the transaction. The main advantages of annotation transactions are as follows.
(1). The development team agreed to define the programming style of the transaction.
(2). Ensure that the execution time of the transaction is as short as possible, do not interspersed with other network operations such as Rpc/http request or split to the periphery of the transaction.
(3). Not all methods require transactions, only one record is modified, read-only operations do not require transactions. five. Unit Test

Writing unit test methods test the service class that is written

public class Seckillserviceimpltest extends Basetest {private final Logger Logger = Loggerfactory.getlogger (this.ge

    Tclass ());

    @Autowired private Seckillservice Seckillservice; @Test public void Testgetseckilllist () throws Exception {list<seckill> List = Seckillservice.getseckill
        List ();
    Logger.info ("list={}", list);
        @Test public void Testgetbyid () throws Exception {Long id = 1000;
        Seckill Seckill = Seckillservice.getseckillbyid (ID);
    Logger.info ("seckill={}", Seckill);
        }//test code Complete logic, note repeatable @Test public void Testseckilllogic () throws Exception {Long id = 1002;
        Exposer Exposer = Seckillservice.exportseckillurl (ID);
            if (exposer.isexposed ()) {Logger.info ("exposer={}", Exposer);
            Long phone = 13631231234L;
            String MD5 = EXPOSER.GETMD5 (); try {seckillexecution execution = Seckillservice.executeseckill (ID, phone, MD5);
            Logger.info ("execution={}", execution);
            catch (Repeatkillexception e) {logger.error (E.getmessage ());
            catch (Seckillcloseexception e) {logger.error (E.getmessage ());
                }catch (Exception e) {e.printstacktrace ();
            Logger.error (E.getmessage ());
        } else {//sec kill not open Logger.error ("exposer={}", Exposer);
        @Test public void Testexecuteseckillprocedure () throws Exception {long seckillid = 1003;
        Long phone = 13631231234L;
        Exposer exposer = Seckillservice.exportseckillurl (seckillid);
            if (exposer.isexposed ()) {String MD5 = EXPOSER.GETMD5 ();
            Seckillexecution execution = Seckillservice.executeseckill (seckillid, phone, MD5);
        Logger.info (Execution.getstateinfo ());
 }
    }

}

Article address: http://www.haha174.top/article/details/251844
Source Address: https://github.com/haha174/seckill.git
Tutorial Address : http://www.imooc.com/learn/631

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.