---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
packageorg.seckill.service.impl;importjava.util.Date;importjava.util.List;importorg.seckill.dao.SeckillDao;importorg.seckill.dao.SuccessKilledDao;importorg.seckill.dto.Exposer;importorg.seckill.dto.SeckillExecution;importorg.seckill.entity.Seckill;importorg.seckill.entity.SuccessKilled;importorg.seckill.enums.SeckillStatEnum;importorg.seckill.exception.RepeatKillExeception;importorg.seckill.exception.SeckillCloseException;importorg.seckill.exception.SeckillException;importorg.seckill.service.SeckillService;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;importorg.springframework.util.DigestUtils;//@Component @service @Dao @Controller
@Servicepublic class SeckillServiceImpl implementsSeckillService {private Logger logger = LoggerFactory.getLogger(this.getClass());//注入Service依赖
@Autowired //在Spring 查找Dao类型的实例(Mybatis实现的,),并注入。不在需要自己new 实例//还有@Resource,@Inject等J2EE规范的注解
privateSeckillDao seckillDao;
@AutowiredprivateSuccessKilledDao successKilledDao;//md5盐值字符串,用于混淆MD5
private final String slat = "sldijfldkjfpaojj@#(#$sldfj`123";
@Overridepublic ListgetSeckillList() {return seckillDao.queryAll(0, 4);
}
@Overridepublic Seckill getById(longseckillId) {//TODO Auto-generated method stub
returnseckillDao.queryById(seckillId);
}
@Overridepublic Exposer exportSeckillUrl(longseckillId) {
Seckill seckill=seckillDao.queryById(seckillId);if(seckill == null){return new Exposer(false,seckillId);
}
Date startTime=seckill.getStartTime();
Date endTime=seckill.getEndTime();//系统当前时间
Date nowTime = newDate();if(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(longseckillId){
String base= seckillId+"/"+slat;
String md5=DigestUtils.md5DigestAsHex(base.getBytes());returnmd5;
}
@Overridepublic SeckillExecution executeSeckill(long seckillId, longuserPhone, String md5)throwsSeckillException, RepeatKillExeception, SeckillCloseException {if(md5==null|| !md5.equals(getMD5(seckillId))){throw new SeckillException("seckill data rewrite");
}//执行秒杀逻辑:减库存 + 记录购买行为
Date nowTime = newDate();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 newSeckillExecution(seckillId,SeckillStatEnum.SUCCESS);
}
}
}catch(SeckillCloseException e1) {throwe1;
}catch(RepeatKillExeception e2) {throwe2;
}catch(Exception e){
logger.error(e.getMessage(),e);//所有编译期异常 转化为运行期异常//spring事务会做roll back
throw new SeckillException("seckill inner error : "+e.getMessage());
}
}
}
spring-service.xml
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">
---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声明式事务配置---------------------------------------------------------
建议:使用注解而不是XML控制事务
事务要小心设计
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
使用AOP的方式配置不推荐,对于真正需要标注的方法定位不精确。
SeckillServiceImpl.java :需要使用事务管理的方法添加@Transactional注解
使用注解控制事务方法的优点:
1、开发团队达成一致约定,明确标注事务方法的编程风格。
ps:使用aop管理事务会造成可能遗忘需要使用什么方法命名等问题
2、保证事务方法的执行时间尽可能短,不要穿插其他网络操作rpc/http等或者剥离到事务外部。
ps:因为这些操作一次要几毫秒到几十毫秒,影响事务速度。
3、不是所有的方法都需要事务,如只有一条修改操作,只读操作不需要事务控制。
ps:如果在配置文件里配置永久使用aop控制事务,不同的人的命名习惯可能会给不需要事务的方法添加事务
@Override
@Transactional/** 使用注解控制事务方法的优点:
* 1、开发团队达成一致约定,明确标注事务方法的编程风格。
* ps:使用aop管理事务会造成可能遗忘需要使用什么方法命名等问题
* 2、保证事务方法的执行时间尽可能短,不要穿插其他网络操作rpc/http等或者剥离到事务外部。
* ps:因为这些操作一次要几毫秒到几十毫秒,影响事务速度。
* 3、不是所有的方法都需要事务,如只有一条修改操作,只读操作不需要事务控制。
* ps:如果在配置文件里配置永久使用aop控制事务,不同的人的命名习惯可能会给不需要事务的方法添加事务
**/
public SeckillExecution executeSeckill(long seckillId, longuserPhone, String md5)throwsSeckillException, RepeatKillExeception, SeckillCloseException {if(md5==null|| !md5.equals(getMD5(seckillId))){throw new SeckillException("seckill data rewrite");
}//执行秒杀逻辑:减库存 + 记录购买行为
Date nowTime = newDate();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 newSeckillExecution(seckillId,SeckillStatEnum.SUCCESS);
}
}
}catch(SeckillCloseException e1) {throwe1;
}catch(RepeatKillExeception e2) {throwe2;
}catch(Exception e){
logger.error(e.getMessage(),e);//所有编译期异常 转化为运行期异常//spring事务会做roll back
throw new SeckillException("seckill inner error : "+e.getMessage());
}
}
---4-1 完成Service集成测试---------------------------------------------------------
1.logback配置
logback-test.xml place it into a directory accessible from the class path(放在classpath下:resources下)
public void testGetSeckillList() {
List list= seckillService.getSeckillList();
logger.info("list={}",list);
}
打印日志可以用占位符,输出在{}内
来自一个代码洁癖患者的忠告:
关于logback文档警告问题的解决:
在文档头加入空的dtd即可:
参考:
http://stackoverflow.com/questions/5731162/xml-schema-or-dtd-for-logback-xml
\seckill\src\main\resources\logback.xml
%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
2.JUnit 测试类
packageorg.seckill.service;importjava.util.List;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.seckill.dto.Exposer;importorg.seckill.dto.SeckillExecution;importorg.seckill.entity.Seckill;importorg.seckill.exception.RepeatKillExeception;importorg.seckill.exception.SeckillCloseException;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.test.context.ContextConfiguration;importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring/spring-dao.xml","classpath:spring/spring-service.xml"})public classSeckillServiceImplTest {private final Logger logger = LoggerFactory.getLogger(this.getClass());
@AutowiredprivateSeckillService seckillService;
@Testpublic void testGetSeckillList() throwsException{
List list=seckillService.getSeckillList();
logger.info("list={}",list);
}
@Testpublic void testGetById() throwsException{long id = 1000;
Seckill seckill=seckillService.getById(id);
logger.info("seckill={}",seckill);
}
@Testpublic void testExportSeckillUrl() throwsException{long id = 1000;
Exposer exposer=seckillService.exportSeckillUrl(id);
logger.info("exposere={}",exposer.toString());/** exposed=true,
* md5=76e96c3b47df23d4239478bf599aae92
**/}
@Testpublic void testExecuteSeckill() throwsException{long id = 1000;long phone = 13411112222L;
String md5= "76e96c3b47df23d4239478bf599aae92";//SeckillExecution正确返回初次执行,SeckillCloseException,RepeatKillExeception(同id+phone重复执行时)都是正确期待结果
try{
SeckillExecution execution=seckillService.executeSeckill(id, phone, md5);
logger.info("SeckillExecution={}",execution);
}catch(SeckillCloseException e) {
logger.error(e.getMessage());
}catch(RepeatKillExeception e) {
logger.error(e.getMessage());
}
}
@Test//结合3,4组成逻辑测试方法//测试代码完整逻辑,注意可重复执行
public void testSeckillLogic() throwsException{long id = 1000;
Exposer exposer=seckillService.exportSeckillUrl(id);if(exposer.isExposed()){
logger.info("exposere={}",exposer.toString());long phone = 13411112222L;
String md5=exposer.getMd5();//SeckillExecution正确返回初次执行,SeckillCloseException,RepeatKillExeception都是正确期待结果
try{
SeckillExecution execution=seckillService.executeSeckill(id, phone, md5);
logger.info("SeckillExecution={}",execution);
}catch(SeckillCloseException e) {
logger.error(e.getMessage());
}catch(RepeatKillExeception e) {
logger.error(e.getMessage());
}
}else{//秒杀未开启
logger.warn("exposer={}",exposer);
}
}
}
spring事务管理该过程:
13:47:56.706 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Creating a new SqlSession
13:47:56.716 [main] DEBUG org.mybatis.spring.SqlSessionUtils -Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2049a9c1]
13:47:56.725 [main] DEBUG o.m.s.t.SpringManagedTransaction - JDBC Connection [com.mchange.v2.c3p0.impl.NewProxyConnection@934b6cb]will be managed by Spring
13:47:56.733 [main] DEBUG o.s.dao.SeckillDao.reduceNumber - ==> Preparing: update seckill set number = number - 1 where seckill_id = ? and start_time <= ? and end_time >= ? and number > 0;
13:47:56.784 [main] DEBUG o.s.dao.SeckillDao.reduceNumber - ==> Parameters: 1000(Long), 2017-07-10 13:47:56.698(Timestamp), 2017-07-10 13:47:56.698(Timestamp)
13:47:56.855 [main] DEBUG o.s.dao.SeckillDao.reduceNumber - <== Updates: 1
13:47:56.856 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2049a9c1]
13:47:56.856 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2049a9c1] from current transaction
13:47:56.856 [main] DEBUG o.s.d.S.insertSuccessKilled - ==> Preparing: insert ignore into Success_killed(seckill_id,user_phone,state) values(?,?,0);
13:47:56.858 [main] DEBUG o.s.d.S.insertSuccessKilled - ==> Parameters: 1000(Long), 13411112222(Long)
13:47:56.970 [main] DEBUG o.s.d.S.insertSuccessKilled - <== Updates: 1
13:47:56.980 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2049a9c1]
13:47:56.981 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2049a9c1] from current transaction
13:47:56.984 [main] DEBUG o.s.d.S.queryByIdWithSeckill - ==> Preparing: select sk.seckill_id, sk.user_phone, sk.state, sk.create_time, s.seckill_id "seckill.seckill_id", s.name "seckill.name", s.number "seckill.number", 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 = ? and sk.user_phone = ?;
13:47:56.984 [main] DEBUG o.s.d.S.queryByIdWithSeckill - ==> Parameters: 1000(Long), 13411112222(Long)
13:47:57.013 [main] DEBUG o.s.d.S.queryByIdWithSeckill - <== Total: 1
13:47:57.022 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2049a9c1]
13:47:57.023 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Transaction synchronization committing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2049a9c1]
13:47:57.023 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Transaction synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2049a9c1]
13:47:57.023 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2049a9c1]
13:47:57.077 [main] INFO o.s.service.SeckillServiceImplTest - SeckillExecution=org.seckill.dto.SeckillExecution@7d898981
*/