Spring事务系列

来源:互联网 发布:漫步者音响推荐知乎 编辑:程序博客网 时间:2024/06/05 20:46

一、Spring 的编程式事务管理

1. 基于底层 API 的编程式事务管理

根据PlatformTransactionManager、TransactionDefinition 和 TransactionStatus 三个核心接口,我们完全可以通过编程的方式来进行事务管理。代码如下:

@Servicepublic class BankServiceImpl implements BankService {    private BankDao bankDao;    private TransactionDefinition txDefinition;    private PlatformTransactionManager txManager;    ......    public boolean transfer(Long fromId, Long toId, double amount) {        TransactionStatus txStatus = txManager.getTransaction(txDefinition);        boolean result = false;        try {            result = bankDao.transfer(fromId, toId, amount);            txManager.commit(txStatus);        } catch (Exception e) {            result = false;            txManager.rollback(txStatus);            System.out.println("Transfer Error!");        }        return result;    }}

2. 基于 TransactionTemplate 的编程式事务管理

二、Spring 的声明式事务管理

maven依赖:

   <properties>        <spring.version>4.3.6.RELEASE</spring.version>        <junit.version>4.12</junit.version>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>    </properties>    <dependencies>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-core</artifactId>            <version>${spring.version}</version>            <exclusions>                <exclusion>                    <artifactId>commons-logging</artifactId>                    <groupId>commons-logging</groupId>                </exclusion>            </exclusions>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-context</artifactId>            <version>${spring.version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-beans</artifactId>            <version>${spring.version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-jdbc</artifactId>            <version>${spring.version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-tx</artifactId>            <version>${spring.version}</version>        </dependency>        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <version>5.1.26</version>        </dependency>        <dependency>            <groupId>com.alibaba</groupId>            <artifactId>druid</artifactId>            <version>1.0.21</version>        </dependency>    </dependencies>

spring-dao.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"       xmlns:tx="http://www.springframework.org/schema/tx"       xmlns:util="http://www.springframework.org/schema/util"       xsi:schemaLocation="            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">    <bean id="parentDataSource" class="com.alibaba.druid.pool.DruidDataSource"           destroy-method="close"  abstract="true" init-method="init" >        <!-- 初始化连接大小 -->        <property name="initialSize" value="2" />        <!-- 连接池最大使用连接数量 -->        <property name="maxActive" value="10" />        <!-- 连接池最小空闲 -->        <property name="minIdle" value="5" />        <!-- 获取连接最大等待时间 -->        <property name="maxWait" value="30000" />        <!-- <property name="poolPreparedStatements" value="true" /> -->        <!-- <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> -->        <property name="validationQuery" value="SELECT 1" />        <property name="testOnBorrow" value="false" />        <property name="testOnReturn" value="false" />        <property name="testWhileIdle" value="true" />        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->        <property name="timeBetweenEvictionRunsMillis" value="60000" />        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->        <property name="minEvictableIdleTimeMillis" value="25200000" />        <!-- 打开removeAbandoned功能 -->        <property name="removeAbandoned" value="true" />        <!-- 1800秒,也就是30分钟 -->        <property name="removeAbandonedTimeout" value="1800" />        <!-- 关闭abanded连接时输出错误日志 -->        <property name="logAbandoned" value="true" />        <!-- 监控数据库 -->        <!-- <property name="filters" value="stat" /> -->        <property name="filters" value="mergeStat" />    </bean>    <!-- 配置数据源-->    <bean id="masterDataSource" parent="parentDataSource">        <property name="url" value="#{jdbc['master.jdbc.url']}" />        <property name="username" value="#{jdbc['master.jdbc.username']}" />        <property name="password" value="#{jdbc['master.jdbc.password']}" />        <property name="driverClassName" value="#{jdbc['master.jdbc.driver']}" />        <property name="maxActive" value="15" />    </bean>    <!--Spring JdbcTemplate-->    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">        <property name="dataSource" ref="masterDataSource"/>    </bean>    <!-- 配置事务管理器 -->    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="dataSource" ref="masterDataSource" />    </bean>    <!-- 启用事物注解 -->    <tx:annotation-driven transaction-manager="transactionManager" /></beans>

以用户下单为例,譬如下单分为两个步骤:更新商品库存和创建订单服务两步,代码如下:

/** * ${DESCRIPTION} * * @author Ricky Fung * @create 2017-03-03 10:27 */@Service("orderBookingService")public class OrderBookingServiceImpl implements OrderBookingService {    @Autowired    private GoodsItemDao goodsItemDao;    @Autowired    private OrderDao orderDao;    @Transactional(rollbackFor = {BookFailureException.class})    @Override    public boolean book(User user, Order order) throws BookFailureException {        boolean success = true;        int update;        for (OrderItem item : order.getItems()){            update = goodsItemDao.updateStock(item.getId(), item.getQuantity());            if(update<1){                success = false;                break;            }        }        if(success){    //更新库存成功            update = orderDao.insert(order);            if(update>0){                return true;            }        }        throw new BookFailureException("book failure");    }}

参考资料

分布式事务系列(1.2)Spring的事务体系:https://yq.aliyun.com/articles/39046?spm=5176.100239.blogcont39044.27.mmXvhw

0 0
原创粉丝点击