当前位置: 首页 > news >正文

专门做推广的公司合肥正规的seo公司

专门做推广的公司,合肥正规的seo公司,宝塔安装wordpress,响应式手机模板WordPress在某些业务场景下,如果一个请求中,需要同事写入多张表的数据,但为了保证操作的原子性(要么同事插入数据成功,要么同事插入失败),例如,当我们创建用户的时候,往往会给用户…

在某些业务场景下,如果一个请求中,需要同事写入多张表的数据,但为了保证操作的原子性(要么同事插入数据成功,要么同事插入失败),例如,当我们创建用户的时候,往往会给用户赋予角色信息,以及菜单权限信息,此时就需要一个接口插入多张表的数据,我们一般会用spring事务避免数据不一致的情况。

spring事务用起来也比较简单,一个简单的注解:@Transactional,就能轻松搞定事务

但是,在一些特殊场景下,事务会失效,具体哪些场景,让我们接下来分析一下。

🚀一、失效场景集结

🚀二、事务不生效场景

🏮1.访问权限问题

Java的访问权限主要有四种,private、default、protected、public,他们的权限从左到右,依次变大。

但如果我们在开发过程中,把有某些事务方法,定义了错误的访问权限,就会导致事务功能出问题。

比如:设置方法的访问权限为private的了。

@Service
public class UserService {@Transactionalprivate void add(User user) {saveData(user);saveRole(user);}
}

add方法的访问权限被定义成了private,这样就会导致事务失效,spring要求被代理方法必须是public的。

在源码中,AbstractFallbackTransactionAttributeSource类的computeTransactionAttribute方法中有个判断,如果目标方法不是public,则TransactionAttribute返回null,即不支持事务。

protected TransactionAttribute computeTransactionAttribute(Method method, @Nullable Class<?> targetClass) {// Don't allow no-public methods as required.if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {return null;}// The method may be on an interface, but we need attributes from the target class.// If the target class is null, the method will be unchanged.Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);// First try is the method in the target class.TransactionAttribute txAttr = findTransactionAttribute(specificMethod);if (txAttr != null) {return txAttr;}// Second try is the transaction attribute on the target class.txAttr = findTransactionAttribute(specificMethod.getDeclaringClass());if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {return txAttr;}if (specificMethod != method) {// Fallback is to look at the original method.txAttr = findTransactionAttribute(method);if (txAttr != null) {return txAttr;}// Last fallback is the class of the original method.txAttr = findTransactionAttribute(method.getDeclaringClass());if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {return txAttr;}}return null;}

也就是说,如果我们自定义的事务方法,即目标方法,它的访问权限不是public,而是private、protected、default的话,spring则不会提供事务功能。、

🏮2.方法用final修饰

 某个方法不想被子类重载,这时可以将方法定义成final的,普通方法这样定义是没问题的,但如果将事务方法定义成final。例如:

@Service
public class UserService {@Transactionalpublic final void add(User user){saveData(user);saveRoleData(user);}
}

add()方法被定义成了final的,会导致事务失效。

why?

因为spring事务底层使用了aop,也就是通过jdk动态代理或者cglib,帮我们生成了代理类,在代理类中实现的事务功能。

但如果某个方法用final修饰了,那么在他的代理类中,就无法重写该方法,而添加事务功能。

🔔注意:如果某个方法是static的,同样无法通过动态代理,变成事务方法。

🏮3.方法内部调用

有时候我们需要在某个业务方法(Service类),调用另外一个事务方法,比如:

@Service
public class UserService {@Autowiredprivate UserMapper userMapper;public void add(User user) {userMapper.insertUser(user);updateStatus(user);}@Transactionalpublic void updateStatus(User user) {doSameThing();}
}

在代码中,事务方法add中,直接调用事务方法updateStatus,updateStatus方法拥有事务的能力是因为spring aop生成代理了对象,但是这种方法直接调用了this对象的方法,所以updateStatus方法不会生成事务。

因此,在同一个类中的方法直接内部调用,会导致事务失效。

那如果有些场景,确实需要在同一个类的某个方法中,调用它自己的另外一个方法,How to do?

🔔3.1新加一个Service方法

这个方法比较简单,只需要新加一个Service方法,把@Transactional注解加到新Service方法上,把需要事务执行的代码移到新方法中。具体代码如下:

@Servcie
public class ServiceA {@Autowiredprivate ServiceB serviceB;public void save(User user) {queryData1();queryData2();serviceB.doSave(user);}}@Servciepublic class ServiceB {@Transactional(rollbackFor=Exception.class)public void doSave(User user) {addData1();updateData2();}}

🔔3.2在该Service类中注入自己

如果不想再新加一个Service类,在该Service类中注入自己也是一种选择,具体代码如下:

@Servcie
public class ServiceA {@Autowiredprivate ServiceA serviceA;public void save(User user) {queryData1();queryData2();serviceA.doSave(user);}@Transactional(rollbackFor=Exception.class)public void doSave(User user) {addData1();updateData2();}}

这种做法不会造成循环依赖问题,其实spring ioc内部的三级缓存保证了它不会出现循环依赖问题。

🔔3.3通过AopContent类

在该Service类中使用AopContext.currentProxy()获取代理对象

3.2中确实可以解决问题,但是代码看起来不直观,还可以通过在该Service类中使用AOPProxy获取代理对象,实现相同的功能。具体代码如下:

@Servcie
public class ServiceA {public void save(User user) {queryData1();queryData2();((ServiceA)AopContext.currentProxy()).doSave(user);}@Transactional(rollbackFor=Exception.class)public void doSave(User user) {addData1();updateData2();}}

🏮4.未被spring管理

在开发的过程中,使用spring事务的前提是:对象要被spring管理,需要创建Bean实例。

通常情况下,通过@Controller、@Service、@Component、@Repository等注解,可以自动实现bean实例化和依赖注入的功能。

那此时的失效就比较明显的知道了,那就是Service类上忘加@Service的注解了。

🏮5.多线程调用

在实际项目开发中,多线程的使用场景还是挺多的,如果spring事务用在多线程场景中,会出现什么问题呢?

@Slf4j
@Service
public class UserService {@Autowiredprivate UserMapper userMapper;@Autowiredprivate RoleService roleService;@Transactionalpublic void add(User user) throws Exception {userMapper.insertUser(user);new Thread(() -> {roleService.doOtherThing();}).start();}
}@Service
public class RoleService {@Transactionalpublic void doOtherThing() {System.out.println("保存role表数据");}
}

从代码中,我们可以看到事务方法add中,调用了事务方法doOtherThing,但是事务方法doOtherThing是在另外一个线程中调用的。

这样会导致两个方法不在同一个线程中,获取到的数据库连接不一样,从而是两个不同的事务,如果想doOtherThing方法中跑了异常,add方法也回滚是不可能的。

spring的事务是通过数据库连接来实现的,当前线程中保存了一个map,key是数据源,value是数据库连接。

private static final ThreadLocal<Map<Object, Object>> resources =new NamedThreadLocal<>("Transactional resources");

我们说的同一个事务,其实是指同一个数据库连接,只有拥有同一个数据库连接才能同事提交和回滚,如果在不同的线程,拿到的数据库连接肯定是不一样,所以是同的事务。

🏮6.表不支持事务

在mysql5之前,默认的数据库引擎是myisam。

它的好处是索引文件和数据库文件时分开存储的,对于查多写少的单表操作,性能比innodb更好。

但是它有一个很致命的问题:不支持事务。

如果只是单表操作还好,不会出现太大的问题,但如果需要联合查询,因其不支持事务,数据极有可能出现不完整的情况。

此外,myisam还不支持行锁和外键。

有时候我们在开发过程中,发现某张表的事务一直没有生效,那不一定时spring事务的问题,可能时数据库不支持事务。

🏮7.未开启事务

有时候,事务没有生效的根本原因时没有开启事务。

如果时spring boot项目,那么你不用担心,因为spring boot通过DataSourceTransactionManagerAutoConfiguration类,已经帮你开启了事务。你所要做的事情很简单,只需要配置spring.datasource相关参数即可。

但如果你使用的还是传统的spring项目,则需要在applicationContext.xml文件中,手动配置事务相关参数。如果忘了配置,事务肯定是不会生效的。

具体配置如下信息:

<!-- 配置事务管理器 --> 
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager"> <property name="dataSource" ref="dataSource"></property> 
</bean> 
<tx:advice id="advice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" propagation="REQUIRED"/></tx:attributes> 
</tx:advice> 
<!-- 用切点把事务切进去 --> 
<aop:config> <aop:pointcut expression="execution(* com.susan.*.*(..))" id="pointcut"/> <aop:advisor advice-ref="advice" pointcut-ref="pointcut"/> 
</aop:config> 

如果在pointcut标签中的切入点匹配规则,配错了的话,有些类的事务也不会生效。

🚀三、事务不回滚

🏮1.错误的传播特性

在使用@Transactional注解时,是可以指定propagation参数的。

该参数的作用是指定事务的传播特性,spring目前支持7种传播特性。

类型描述
REQUIRED如果当前上下文中存在事务,那么加入该事务,如果不存在事务,创建一个事务,这是默认的传播属性值。
SUPPORTS如果当前上下文存在事务,则支持事务加入事务,如果不存在事务,则使用非事务的方式执行。
MANDATORY如果当前上下文中存在事务,否则抛出异常。
REQUIRES_NEW每次都会新建一个事务,并且同时将上下文中的事务挂起,执行当前新建事务完成以后,上下文事务恢复再执行。
NOT_SUPPORTED如果当前上下文中存在事务,则挂起当前事务,然后新的方法在没有事务的环境中执行。
NEVER如果当前上下文中存在事务,则抛出异常,否则在无事务环境上执行代码。
NESTED如果当前上下文中存在事务,则嵌套事务执行,如果不存在事务,则新建事务。

如果我们在手动设置propagation参数的时候,把传播特性设置错了,比如:

@Service
public class UserService {@Transactional(propagation = Propagation.NEVER)public void add(User user) {saveData(user);updateData(user);}
}

add方法的事务传播特性定义成了Propagation.NEVER,这种类型的传播特性不支持事务,如果有事务则会抛异常。

目前只有这三种传播特性才会创建新事务:REQUIRED,REQUIRES_NEW,NESTED。

🏮2.自己吞了异常

事务不会回滚,最常见的问题是:开发者在代码中手动try...catch了异常。比如:

@Slf4j
@Service
public class UserService {@Transactionalpublic void add(User user) {try {saveData(user);updateData(user);} catch (Exception e) {log.error(e.getMessage(), e);}}
}

🏮3.手动抛了别的异常

开发者没有手动捕获异常,但如果抛的异常不正确,spring事务也不会回滚。

@Slf4j
@Service
public class UserService {@Transactionalpublic void add(UserModel userModel) throws Exception {try {saveData(userModel);updateData(userModel);} catch (Exception e) {log.error(e.getMessage(), e);throw new Exception(e);}}
}

该情况是开发人员自己捕获了异常,又手动抛出了异常:Exception,事务同样不会回滚。

因为spring事务,默认情况下只会RuntimeException(运行时异常)Error(错误),对于普通的Exception(非运行时异常),它不会回滚。

🏮4.自定义了回滚异常

在使用@Transactional注解声明事务时,有时我们想自定义回滚的异常,spring也是支持的,可以通过设置rollbackFor参数来进行回滚。

但如果这个参数值设置错了,就会引起很奇怪的问题,比如:

@Slf4j
@Service
public class UserService {@Transactional(rollbackFor = BusinessException.class)public void add(User user) throws Exception {saveData(user);updateData(user);}
}

如果在执行这段代码的时候,保存和更新数据时,程序报错了,抛出了SqlException、DuplicateKeyException等异常。而BusinessException是自定义的异常,报错的异常不属于BusinessException,所以事务也不会回滚。

即使rollbackFor有默认值,但alibaba开发者规范中,还是要求开发人员重新指定该参数。

why?

因为如果使用默认值,一旦程序抛出了Exception,事务不会回滚,这会出现很大的bug,所以,建议一般情况下,将该参数设置成:Exception或Throwable。

🏮5.嵌套事务回滚太多

public class UserService {@Autowiredprivate UserMapper userMapper;@Autowiredprivate RoleService roleService;@Transactionalpublic void add(User user) throws Exception {userMapper.insertUser(user);roleService.doOtherThing();}
}@Service
public class RoleService {@Transactional(propagation = Propagation.NESTED)public void doOtherThing() {System.out.println("保存role表数据");}
}

这种情况使用了嵌套的内部事务,原本是希望调用roleService.doOtherThing方法时,如果出现了异常,只回滚doOtherThing方法里的内容,不回滚userMapper.insertUser里的内容,即回滚保存点,但实际上,insertUser也回滚了。

why?

因为doOtherThing方法出现了异常,没有手动捕获,会继续网上抛,到外层add方法的代理方法中捕获了异常,所以,这种情况是直接回滚了整个事务,不只回滚单个保存点。

怎样才能回滚保存点呢?

@Slf4j
@Service
public class UserService {@Autowiredprivate UserMapper userMapper;@Autowiredprivate RoleService roleService;@Transactionalpublic void add(User user) throws Exception {userMapper.insertUser(user);try {roleService.doOtherThing();} catch (Exception e) {log.error(e.getMessage(), e);}}
}

可以将内部嵌套事务放在try....catch中,并且不继续往上抛异常,这样就能保证,如果内部嵌套事务中出现异常,只回滚内部事务,而不影响外部事务。

🚀四、其他

🏮1.大事务问题

在使用spring事务时,有个让人烦恼的问题,就是大事务问题。通常情况下,我们会在方法上@Transactional注解,添加事务功能,比如:

@Service
public class UserService {@Autowired private RoleService roleService;@Transactionalpublic void add(User user) throws Exception {query1();query2();query3();roleService.save(user);update(user);}
}@Service
public class RoleService {@Autowired private RoleService roleService;@Transactionalpublic void save(User user) throws Exception {query4();query5();query6();saveData(user);}
}

@Transaction注解,如果被加到方法上,缺点就是整个方法都包含在事务当中了。

上面这个例子中,在UserService类中,只有这两行需要事务:

roleService.save(user);
update(user);

在RoleService类中,只有一行需要事务:

saveData(user);

这种写法,会导致所有的query方法也被包含在同一个事务当中。

如果query过多,调用层级很深,有一些查询如果比较耗时的话,会造成整个事务非常耗时,从而造成大事务问题。

大事务问题最好的解决办法,我认为就是编程式事务。

🏮2.编程式事务

上面我们所说的都是围绕@Transactional注解来展开说明的,这些叫做:声明式事务

spring还提供了另一种创建事务的方式,即通过手动编写代码实现的事务,我们把这种事务叫做:编程式事务。比如:

 @Autowiredprivate TransactionTemplate transactionTemplate;...public void save(final User user) {queryData1();queryData2();transactionTemplate.execute((status) => {addData1();updateData2();return Boolean.TRUE;})}

在spring中为了支持编程式事务,专门提供了一个类:TransactionTemplate,在它的execute方法中,就实现了事务的功能。

相较于@Transactional注解声明式事务,建议大家使用基于TransactionTemplate的编程式事务,主要原因如下:

①避免由于spring aop问题,导致事务失效

②能够更小粒度的控制事务范围,更直观。

🔔注意:并不是不使用@Transactional注解开启事务,如果项目中业务逻辑比较简单,并且不经常变动,使用@Transactional注解开启事务是可以的,因为简单,开发更快,注意事务失效的问题就行。


文章转载自:
http://curarize.fwrr.cn
http://archfiend.fwrr.cn
http://affrontedness.fwrr.cn
http://unsteadily.fwrr.cn
http://managerialist.fwrr.cn
http://barf.fwrr.cn
http://imho.fwrr.cn
http://nae.fwrr.cn
http://chamfer.fwrr.cn
http://dolich.fwrr.cn
http://hypophysectomy.fwrr.cn
http://rodenticide.fwrr.cn
http://thromboembolus.fwrr.cn
http://anticorrosion.fwrr.cn
http://calligraphy.fwrr.cn
http://awkward.fwrr.cn
http://genitival.fwrr.cn
http://galactagogue.fwrr.cn
http://worsted.fwrr.cn
http://astrologian.fwrr.cn
http://barrow.fwrr.cn
http://agrestic.fwrr.cn
http://hypopnea.fwrr.cn
http://religionize.fwrr.cn
http://accouterments.fwrr.cn
http://jihad.fwrr.cn
http://tango.fwrr.cn
http://darbies.fwrr.cn
http://seventeenth.fwrr.cn
http://automorphism.fwrr.cn
http://perspiration.fwrr.cn
http://disputed.fwrr.cn
http://limenian.fwrr.cn
http://parnassian.fwrr.cn
http://liquorice.fwrr.cn
http://idc.fwrr.cn
http://deschooler.fwrr.cn
http://incept.fwrr.cn
http://ultrarapid.fwrr.cn
http://irreversibility.fwrr.cn
http://labe.fwrr.cn
http://palely.fwrr.cn
http://equites.fwrr.cn
http://alamanni.fwrr.cn
http://necromimesis.fwrr.cn
http://formulize.fwrr.cn
http://lall.fwrr.cn
http://yarke.fwrr.cn
http://quina.fwrr.cn
http://resit.fwrr.cn
http://recount.fwrr.cn
http://immurement.fwrr.cn
http://carrier.fwrr.cn
http://finish.fwrr.cn
http://fense.fwrr.cn
http://foresail.fwrr.cn
http://prelicense.fwrr.cn
http://enveigle.fwrr.cn
http://piezometrical.fwrr.cn
http://jacana.fwrr.cn
http://cia.fwrr.cn
http://angiosarcoma.fwrr.cn
http://bloodguilty.fwrr.cn
http://behest.fwrr.cn
http://ono.fwrr.cn
http://reginal.fwrr.cn
http://rhythmist.fwrr.cn
http://sculpt.fwrr.cn
http://peroration.fwrr.cn
http://hylomorphism.fwrr.cn
http://complexion.fwrr.cn
http://egg.fwrr.cn
http://responaut.fwrr.cn
http://carotic.fwrr.cn
http://woofy.fwrr.cn
http://boundlessly.fwrr.cn
http://scutter.fwrr.cn
http://before.fwrr.cn
http://ballooning.fwrr.cn
http://intravascular.fwrr.cn
http://shortite.fwrr.cn
http://patrolwoman.fwrr.cn
http://aliquant.fwrr.cn
http://meagerly.fwrr.cn
http://ruffianize.fwrr.cn
http://trestlework.fwrr.cn
http://dyer.fwrr.cn
http://sorriness.fwrr.cn
http://sacque.fwrr.cn
http://polycarbonate.fwrr.cn
http://isodose.fwrr.cn
http://wandoo.fwrr.cn
http://microspectrophotometer.fwrr.cn
http://terebrate.fwrr.cn
http://caressing.fwrr.cn
http://eutaxy.fwrr.cn
http://odd.fwrr.cn
http://nonaddicting.fwrr.cn
http://breechloader.fwrr.cn
http://sheikh.fwrr.cn
http://www.dt0577.cn/news/88623.html

相关文章:

  • 做网站九州科技磁力搜索
  • dede手机网站更新千锋教育的真实性
  • 自己可以做视频网站吗印度疫情为何突然消失
  • 无锡公司做网站seo兼职外包
  • 合肥建网站要多少钱宣传推广的形式有哪些
  • 制作ppt的软件叫什么武汉seo网络营销推广
  • 手机网站后台管理一站式海外推广平台
  • php 企业网站源码成都网站优化排名
  • wordpress xampp建站百度指数搜索榜
  • 广告公司简介介绍seo如何去做优化
  • 网站开发的pc或移动端seo的培训网站哪里好
  • 登封网站建设石家庄百度seo
  • 青海西宁高端网站建设怎么建立公司网站
  • 濮阳网站怎么做seo免费seo软件推荐
  • 在线购物商城系统seo优化培训课程
  • 微信网站开发教程视频吴中seo页面优化推广
  • 宁波网站建设服务公司电hua交换链接的例子
  • 网站建设收费标准资讯模板建站常规流程
  • 行政部网站建设规划学生个人网页设计模板
  • 网站上的流动图片怎么做的网络推广平台
  • 建设独立网站需要什么时候十大计算机培训机构排名
  • 北京装修公司哪家性价比高岳阳seo快速排名
  • 做网站用php还是htmlgoogle安卓版下载
  • 国内做外卖的网站有哪些三只松鼠的软文范例
  • 什么网站做装修的公司官网优化方案
  • 长沙公司建淘宝优化标题都是用什么软件
  • 网站设计过程介绍个人网页模板
  • 专做畜牧招聘网站的百度邮箱登录入口
  • 营销型网站的类型有哪些苏州seo建站
  • 济南seo网站优化公司百度免费打开