Java高並發秒時啊API之Service層1

來源:互聯網
上載者:User

標籤:exception   reduce   tco   inner   尋找   start   業務   byte   ati   

---2-1 使用Spring託管Service依賴理論----------------------------

 

spring ioc優勢(原廠模式):
1.對象建立統一託管
2.規範的生命週期管理
3.靈活的依賴注入
4.一致的擷取對象

 

Spring IOC 功能的理解
DAO依賴+Service依賴最終形成一致提供者;
隨意訪問依賴對象

 

Spring IOC 容器下的 對象 預設都是單例的。

業務對象依賴圖:Spring IOC容器 通過 DI 解決 依賴鏈(對象之間的依賴關係)

SeckillService ->SeckillDao  ->SqlSessionFactry->DataSource...

      ->successKilledDao

Spring-IOC注入方式和情境

本項目IOC使用:

  XML配置

  package-scan

  Annotation註解

 ---2-2 使用Spring託管Service依賴配置---------------------------------------------------------

 

SeckillServiceImpl.java:

  配置spring-service.xml

  標註註解@Service和@Autowired

package org.seckill.service.impl;import java.util.Date;import java.util.List;import org.seckill.dao.SeckillDao;import org.seckill.dao.SuccessKilledDao;import org.seckill.dto.Exposer;import org.seckill.dto.SeckillExecution;import org.seckill.entity.Seckill;import org.seckill.entity.SuccessKilled;import org.seckill.enums.SeckillStatEnum;import org.seckill.exception.RepeatKillExeception;import org.seckill.exception.SeckillCloseException;import org.seckill.exception.SeckillException;import org.seckill.service.SeckillService;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.util.DigestUtils;//@Component @service @Dao @Controller@Servicepublic class SeckillServiceImpl implements SeckillService {    private Logger logger = LoggerFactory.getLogger(this.getClass());        //注入Service依賴    @Autowired //在Spring 尋找Dao類型的執行個體(Mybatis實現的,),並注入。不在需要自己new 執行個體    //還有@Resource,@Inject等J2EE規範的註解    private SeckillDao seckillDao;    @Autowired    private SuccessKilledDao successKilledDao;        //md5鹽值字串,用於混淆MD5    private final String slat = "[email protected]#(#$sldfj`123";    @Override    public List<Seckill> getSeckillList() {        return seckillDao.queryAll(0, 4);    }    @Override    public Seckill getById(long seckillId) {        // TODO Auto-generated method stub        return seckillDao.queryById(seckillId);    }    @Override    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(nowTime.getTime() < startTime.getTime()                || nowTime.getTime() > endTime.getTime()){            return new Exposer(false,seckillId,nowTime.getTime(),startTime.getTime(),                    endTime.getTime());        }        //轉化特定字串的過程,無法復原        String md5 = getMD5(seckillId);//TODO        return new Exposer(true,md5,seckillId);    }    private String getMD5(long seckillId){        String base = seckillId+"/"+slat;        String md5 = DigestUtils.md5DigestAsHex(base.getBytes());        return md5;    }    @Override    public SeckillExecution executeSeckill(long seckillId, long userPhone, String md5)            throws SeckillException, RepeatKillExeception, SeckillCloseException {        if(md5==null|| !md5.equals(getMD5(seckillId))){            throw new SeckillException("seckill data rewrite");        }        //執行秒殺邏輯:減庫存 + 記錄購買行為        Date nowTime = new Date();        try{            int updateCount = seckillDao.reduceNumber(seckillId, nowTime);            if(updateCount <=0){                //沒有更新記錄                throw new SeckillCloseException("seckill is closed");            } else {                //記錄購買行為                int insertCount= successKilledDao.insertSuccessKilled(seckillId, userPhone);                //唯一:insert ignore                 if(insertCount <=0){                    //重複秒殺                    throw new RepeatKillExeception("seckill repeated");                }else {                    //秒殺成功                    SuccessKilled successKilled = successKilledDao.queryByIdWithSeckill(seckillId, userPhone);                    //return new SeckillExecution(seckillId,1,"秒殺成功",successKilled);                    return new  SeckillExecution(seckillId,SeckillStatEnum.SUCCESS);                }            }                    } catch (SeckillCloseException e1) {            throw e1;        } catch (RepeatKillExeception e2) {            throw e2;        }catch (Exception e){            logger.error(e.getMessage(),e);            //所有編譯期異常 轉化為運行期異常            //spring事務會做roll back            throw new SeckillException("seckill inner error : "+e.getMessage());        }    }}

 

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"        xsi:schemaLocation="http://www.springframework.org/schema/beans            http://www.springframework.org/schema/beans/spring-beans-4.1.xsd            http://www.springframework.org/schema/context            http://www.springframework.org/schema/context/spring-context-4.1.xsd">    <!-- 掃描service包下所使用註解的類型 -->    <context:component-scan base-package="org.seckill.service"/></beans>

 ---3-1 使用Spring聲明式事務理論---------------------------------------------------------

1.什麼是聲明式事務

  通過Spring來管理(全自動),解脫事務代碼

2.聲明式事務使用方式:

ProxyFactoryBean + XML  -------> 早期使用方式(2.0)

tx:advice + aop命名空間    ------> 一次配置永久生效

註解@Transactional (推薦) ------>註解控制()

註解控制:在控制事務方法上加入註解,在開發中大家遵守約定。

 

3.事務方法嵌套:

  聲明式事務專屬的概念

  傳播行為--->propagation_required,如果有事務就加入到事務的原有邏輯,如果沒有就建立一個新事務。

 

4.什麼時候復原:

  拋出運行期異常(RuntimeException)

  小心不當的try-catch(如果不小心拋出了編譯期異常,Spring不會復原)

 

 ---3-2 使用Spring聲明式事務配置---------------------------------------------------------

 

 

 ---4-1 完成Service整合測試---------------------------------------------------------

Java高並發秒時啊API之Service層1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.