springboot的出现使得项目中使用事务变得非常简单,有两种使用方式,适合小型项目的注解事务(声明式事务管理),适合大型项目的全局事务。
1、注解事务(次要)
注解事务使用只用两步,开启事务注解功能,使用事务注解功能,并且每步都只有使用一个注解。
第一步
开启事务注解功能@enabletransactionmanagement
在主启动类中添加注解@enabletransactionmanagement
即可。
package com.gx; import org.springframework.boot.springapplication; import org.springframework.boot.autoconfigure.springbootapplication; import org.springframework.transaction.annotation.enabletransactionmanagement; @enabletransactionmanagement //开启事务注解功能 @springbootapplication public class ch09springboottransannoapplication { public static void main(string[] args) { springapplication.run(ch09springboottransannoapplication.class, args); } }
第二步
使用事务注解功能@transactional
在service接口实现类或接口实现类方法上添加@transactional
即可。
package com.gx.service.impl; import com.gx.service.studentservice; import org.springframework.stereotype.service; import org.springframework.transaction.annotation.transactional; import com.gx.domain.student; @service public class studentserviceimpl implements studentservice { @transactional //使用注解事务 @override public string addstudent(student student) { //业务方法 } }
注意事项:@transactional
必须添加在public修饰的方法上。
2、全局事务(主要)
springboot全局事务主要使用aop切面编程。
第一步
创建切面类@aspect
。
创建一个普通的类,加上@aspect
后该类就是一个切面类了,用于编写事务功能。
同时还需要把该切面类定义为一个配置类,添加注解@configuration
即可。
注意事项:
1、@aspect
将该类定义为切面类,把当前类作为一个切面被容器读取。
2、@configuration
将该类定义为配置类,配置spring容器,注入bean
package com.gx.config; import org.aspectj.lang.annotation.aspect; import org.springframework.context.annotation.configuration; @aspect //定义切面类,把当前类标识为一个切面供容器读取 @configuration //定义配置类 public class transactionadviceconfig { //增强方法 }
第二步
创建第一个方法,返回事务拦截器(transactioninterceptor),声明业务方法的事务属性,并且注册到bean中。
需要返回事务拦截器transactioninterceptor
,就需要new一个transactioninterceptor
。
根据transactioninterceptor
的类可得知,创建一个transactioninterceptor
目前只有两个方法。
public transactioninterceptor() { } public transactioninterceptor(transactionmanager ptm, transactionattributesource tas) { this.settransactionmanager(ptm); this.settransactionattributesource(tas); }
要使用事务,就要有事务管理器transactionmanager
和事务属性transactionattributesource
。
配置事务属性时一般都是通过方法的名字筛选,比如add*
、save*
、delete*
等,所以事务属性使用的是他的子类namematchtransactionattributesource
。
//事务管理器 @autowired private transactionmanager transactionmanager; @bean public transactioninterceptor txadvice() { //声明一个通过方法名字配置事务属性的对象 namematchtransactionattributesource source = new namematchtransactionattributesource(); //返回一个事务拦截器 return new transactioninterceptor(transactionmanager, source); }
通过方法名称设置业务方法事务属性。
namematchtransactionattributesource
类中我们使用的频繁的就两个方法。
setnamemap
其实就是addtransactionalmethod
的集合。
//通过map集合给多个方法或者多类方法设置事务属性 public void setnamemap(map<string, transactionattribute> namemap) { namemap.foreach(this::addtransactionalmethod); } //通过方法名称或一类方法名称和事务属性,给一个方法或一类方法设置事务属性 public void addtransactionalmethod(string methodname, transactionattribute attr) { if (logger.isdebugenabled()) { logger.debug("adding transactional method [" + methodname + "] with attribute [" + attr + "]"); } if (this.embeddedvalueresolver != null && attr instanceof defaulttransactionattribute) { ((defaulttransactionattribute) attr).resolveattributestrings(this.embeddedvalueresolver); } this.namemap.put(methodname, attr); }
设置事务属性。
transactionattribute
:事务属性,有很多实现的实现类,一般使用基于规则的事务属性rulebasedtransactionattribute
。
功能大部分在他的父类defaulttransactiondefinition
中。
只写一小部分,其他可以根据业务需求写事务属性。
//配置一个事务属性(只读) rulebasedtransactionattribute readonlytx = new rulebasedtransactionattribute(); //是否只读 readonlytx.setreadonly(true); //事务传播行为 readonlytx.setpropagationbehavior(transactiondefinition.propagation_required); //通过方法名称设置业务方法事务属性 map<string, transactionattribute> txmap = new hashmap<>(); txmap.put("get*", readonlytx);
再添加到namematchtransactionattributesource
中
source.setnamemap(txmap);
设置事务属性的方法
- 1、事务传播行为 setpropagationbehavior();
- 2、事务隔离级别 setisolationlevel();
- 3、事务超时时间 settimeout();
- 4、事务只读 setreadonly();
- 5、设置事务名称 setname();
- 6、设置回滚规则 setrollbackrules();
事务属性。(扩展)
事务传播行为
事务行为 | 说明 |
---|---|
propagation_required | 支持当前事务,假设当前没有事务。就新建一个事务 |
propagation_supports | 支持当前事务,假设当前没有事务,就以非事务方式运行 |
propagation_mandatory | 支持当前事务,假设当前没有事务,就抛出异常 |
propagation_requires_new | 新建事务,假设当前存在事务。把当前事务挂起 |
propagation_not_supported | 以非事务方式运行操作。假设当前存在事务,就把当前事务挂起 |
propagation_never | 以非事务方式运行,假设当前存在事务,则抛出异常 |
propagation_nested | 如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与propagation_required类似的操作。 |
事务隔离级别,事务的隔离级别只用4种但是spring提供有5种。(spring的隔离级别名字与数据库中的不一样)
隔离级别 | 说明 | 脏读 | 幻读 | 不可重复读 |
---|---|---|---|---|
isolation_default | 默认隔离级别,每种数据库支持的事务隔离级别不一样,根据使用的数据库改变。 | - | - | - |
isolation_read_uncommitted | 读未提交,即能够读取到没有被提交的数据。 | 是 | 是 | 是 |
isolation_read_committed | 读已提交,即能够读到那些已经提交的数据。 | 否 | 是 | 是 |
isolation_repeatable_read | 重复读取,即在数据读出来之后加锁。这个事务不结束,别的事务无法操作这条数据。 | 否 | 否 | 是 |
isolation_serializable | 串行化,最高的事务隔离级别,不管多少事务,挨个运行完一个事务的所有子事务之后才可以执行另外一个事务里面的所有子事务。 | 否 | 否 | 否 |
第三步
配置适配器(advisor),增强事务。
创建适配器(一个普通的方法返回advisor)。
advisor(顾问)是由切入点和advice(通知)组成的,但是advisor是一个接口,需要实现它实现类defaultpointcutadvisor
,并且传入参数切入点和adivce。
@bean public advisor txadviceadvisor() { //增强事务,关联切入点和事务属性 return new defaultpointcutadvisor(切入点, advice); }
配置切入点。
//配置切入点表达式 : 指定哪些包中的类使用事务,设置为静态类常量 private static final string aop_pointcut_expression = "execution (* com.***.service.*.*(..))"; //一下内容放在适配器方法内 //配置事务切入点表达式 aspectjexpressionpointcut pointcut = new aspectjexpressionpointcut(); pointcut.setexpression(aop_pointcut_expression);
关联切入点和advice。
//增强事务,关联切入点和事务属性 return new defaultpointcutadvisor(pointcut, txadvice());
第四步
重启测试!
最后奉上aop全局事务全部代码
package com.gx.config; import org.aspectj.lang.annotation.aspect; import org.springframework.aop.advisor; import org.springframework.aop.aspectj.aspectjexpressionpointcut; import org.springframework.aop.support.defaultpointcutadvisor; import org.springframework.beans.factory.annotation.autowired; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import org.springframework.transaction.platformtransactionmanager; import org.springframework.transaction.transactiondefinition; import org.springframework.transaction.transactionmanager; import org.springframework.transaction.interceptor.*; import javax.sql.datasource; import java.util.collections; import java.util.hashmap; import java.util.map; @aspect //定义切面类,把当前类标识为一个切面供容器读取 @configuration //定义配置类 public class transactionadviceconfig { //事务的超时时间为10秒 private static final int tx_method_timeout = 10; //配置切入点表达式 : 指定哪些包中的类使用事务 private static final string aop_pointcut_expression = "execution (* com.***.service.*.*(..))"; //事务管理器 @autowired private transactionmanager transactionmanager; /** * 声明业务方法的事务属性 */ @bean public transactioninterceptor txadvice() { /** * 这里配置只读事务 */ rulebasedtransactionattribute readonlytx = new rulebasedtransactionattribute(); readonlytx.setreadonly(true);//是否只读 readonlytx.setpropagationbehavior(transactiondefinition.propagation_required);//事务的传播行为 /** * 必须带事务 * 当前存在事务就使用当前事务,当前不存在事务,就开启一个新的事务 */ rulebasedtransactionattribute requiredtx = new rulebasedtransactionattribute(); //检查型异常也回滚 requiredtx.setrollbackrules( collections.singletonlist(new rollbackruleattribute(exception.class))); requiredtx.setpropagationbehavior(transactiondefinition.propagation_required); requiredtx.settimeout(tx_method_timeout); /** * 无事务地执行,挂起任何存在的事务 */ rulebasedtransactionattribute notx = new rulebasedtransactionattribute(); notx.setpropagationbehavior(transactiondefinition.propagation_not_supported); /** * 设置方法对应的事务 */ map<string, transactionattribute> txmap = new hashmap<>(); //只读事务 txmap.put("get*", readonlytx); txmap.put("query*", readonlytx); txmap.put("find*", readonlytx); txmap.put("list*", readonlytx); txmap.put("count*", readonlytx); txmap.put("exist*", readonlytx); txmap.put("search*", readonlytx); txmap.put("fetch*", readonlytx); //无事务 txmap.put("notx*", notx); //写事务 txmap.put("add*", requiredtx); txmap.put("save*", requiredtx); txmap.put("insert*", requiredtx); txmap.put("update*", requiredtx); txmap.put("modify*", requiredtx); txmap.put("delete*", requiredtx); namematchtransactionattributesource source = new namematchtransactionattributesource(); source.setnamemap(txmap); //返回事务拦截器 return new transactioninterceptor(transactionmanager, source); } @bean public advisor txadviceadvisor() { //配置事务切入点表达式 aspectjexpressionpointcut pointcut = new aspectjexpressionpointcut(); pointcut.setexpression(aop_pointcut_expression); //增强事务,关联切入点和事务属性 return new defaultpointcutadvisor(pointcut, txadvice()); } }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论