天天看点

spring事物中的传播及隔离

鍏充簬@Transactional娉ㄨВ锛?h5>娣诲姞浜嬪姟娉ㄨВ

1銆佷娇鐢?propagation 鎸囧畾浜嬪姟鐨勪紶鎾涓? 鍗冲綋鍓嶇殑浜嬪姟鏂规硶琚彟澶栦竴涓簨鍔℃柟娉曡皟鐢ㄦ椂銆傚浣曚娇鐢ㄤ簨鍔? 榛樿鍙栧€间负 REQUIRED, 鍗充娇鐢ㄨ皟鐢ㄦ柟娉曠殑浜嬪姟REQUIRES_NEW: 浜嬪姟鑷繁鐨勪簨鍔? 璋冪敤鐨勪簨鍔℃柟娉曠殑浜嬪姟琚寕璧枫€?

2銆佷娇鐢?isolation 鎸囧畾浜嬪姟鐨勯殧绂荤骇鍒? 鏈€甯哥敤鐨勫彇鍊间负 READ_COMMITTED銆?

3銆侀粯璁ゆ儏鍐典笅 Spring 鐨勫0鏄庡紡浜嬪姟瀵规墍鏈夌殑杩愯鏃跺紓甯歌繘琛屽洖婊? 涔熷彲浠ラ€氳繃瀵瑰簲鐨勫睘鎬ц繘琛岃缃? 閫氬父鎯呭喌涓嬪幓榛樿鍊煎嵆鍙€?銆佷娇鐢?readOnly 鎸囧畾浜嬪姟鏄惁涓哄彧璇? 琛ㄧず杩欎釜浜嬪姟鍙鍙栨暟鎹絾涓嶆洿鏂版暟鎹紝杩欐牱鍙互甯姪鏁版嵁搴撳紩鎿庝紭鍖栦簨鍔? 鑻ョ湡鐨勬槸涓€涓彧璇诲彇鏁版嵁搴撳€肩殑鏂规硶, 搴旇缃?readOnly=true

5銆佷娇鐢?timeout 鎸囧畾寮哄埗鍥炴粴涔嬪墠浜嬪姟鍙互鍗犵敤鐨勬椂闂淬€?

涓汉鐤戦棶鏈変竴浜涳紝缁撳熬鏉ヨ锛岀敤鏁欑▼渚嬪瓙鏉ヨ鍚с€?

鎴戠殑浠g爜濡備笅锛?/h4>

BookShopDao鎺ュ彛
package com.demo.spring.bean;

public interface BookShopDao {

    //鏍规嵁涔︾殑缂栧彿杩斿洖涔︾殑鍗曚环
    public int findBookPriceByIsbn(String isbn);
    //鏍规嵁涔︾殑缂栧彿杩斿洖杈撶殑搴撳瓨
    public void updateBookStock(String isbn);
    //鏇存柊鐢ㄦ埛璐︽埛浣欓
    public void updateUserAccount(String username, int price);
}           
澶嶅埗
瀹炵幇绫?/h5>
package com.demo.spring.bean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository("bookShopDao")
public class BookShopDaoImpl implements BookShopDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int findBookPriceByIsbn(String isbn) {
        // TODO Auto-generated method stub
        String sql = "SELECT price FROM book WHERE isbn=?";
        Integer price = jdbcTemplate.queryForObject(sql, Integer.class, isbn);
        return price;
    }

    @Override
    public void updateBookStock(String isbn) {
        // TODO Auto-generated method stub
        String sql = "SELECT stock FROM book_stock WHERE isbn= ? ";
        Integer stock = jdbcTemplate.queryForObject(sql, Integer.class, isbn);
        if (stock == 0) {
            throw new BookStockException("搴撳瓨涓嶈冻锛侊紒");
        }
        String sql1 = "UPDATE book_stock SET stock=stock-1 WHERE isbn=?";
        jdbcTemplate.update(sql1, isbn);
    }

    @Override
    public void updateUserAccount(String username, int price) {
        // TODO Auto-generated method stub
        String sql1 = "SELECT balance FROM account WHERE username= ? ";
        Integer account = jdbcTemplate.queryForObject(sql1, Integer.class,
                username);
        if (account < price) {
            throw new AccountException("浣欓涓嶈冻锛侊紒");
        }
        String sql = "UPDATE account SET balance=balance-? WHERE username=?";
        jdbcTemplate.update(sql, price, username);
    }

}           
澶嶅埗
BookShopService鎺ュ彛
package com.demo.spring.bean;

public interface BookShopService {
//璐功
public void purchase(String username, String isbn);
}           
澶嶅埗

瀹炵幇绫?/h4>
package com.demo.spring.bean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("bookShopService")
public class BookShopServiceImpl implements BookShopService {


    @Autowired
    private BookShopDao bookShopDao;
// @Transactional(propagation=Propagation.REQUIRES_NEW,isolation=Isolation.READ_COMMITTED,readOnly=true,timeout=5,noRollbackFor=AccountException.class)

    @Transactional
    @Override
    public void purchase(String username, String isbn) {

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // TODO Auto-generated method stub
        int price = bookShopDao.findBookPriceByIsbn(isbn);
        bookShopDao.updateBookStock(isbn);
        bookShopDao.updateUserAccount(username, price);
    }

}           
澶嶅埗

Cashier鎵归噺璐功鎺ュ彛

package com.demo.spring.bean;

import java.util.List;

public interface Cashier {
    //鎵归噺璐功
    public void checkout(String username, List<String> isbns);

}           
澶嶅埗

瀹炵幇绫?/h4>
package com.demo.spring.bean;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service("cashier")
public class CashierImpl implements Cashier {

    @Autowired
    private BookShopService bookShopService;
//    @Transactional
    @Override
    public void checkout(String username, List<String> isbns) {
        // TODO Auto-generated method stub
        for (String isbn : isbns) {
            bookShopService.purchase(username, isbn);
        }

    }

}           
澶嶅埗

璐︽埛浣欓涓嶈冻寮傚父锛堣嚜瀹氫箟寮傚父锛?/h4>
package com.demo.spring.bean;

public class AccountException extends RuntimeException {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public AccountException() {
        super();
        // TODO Auto-generated constructor stub
    }

    public AccountException(String message, Throwable cause,
            boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
        // TODO Auto-generated constructor stub
    }

    public AccountException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

    public AccountException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    public AccountException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }


}           
澶嶅埗

搴撳瓨涓嶈冻寮傚父锛堣嚜瀹氫箟寮傚父锛?/h4>
package com.demo.spring.bean;

public class BookStockException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public BookStockException() {
        super();
        // TODO Auto-generated constructor stub
    }

    public BookStockException(String message, Throwable cause,
            boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
        // TODO Auto-generated constructor stub
    }

    public BookStockException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

    public BookStockException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    public BookStockException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }


}           
澶嶅埗

娴嬭瘯绫?/h4>
package com.demo.spring.bean;

import java.util.Arrays;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainTest {


    private ApplicationContext ctx;
    @Autowired
    private Cashier cashier;
    {
        ctx=new ClassPathXmlApplicationContext("bean.xml");
        cashier=(Cashier) ctx.getBean("cashier");
    }

     @Test
     public void test(){
//         System.out.println(bookShopDao.findBookPriceByIsbn("1001"));
         cashier.checkout("rongrong", Arrays.asList("1001","1002"));
     }



}           
澶嶅埗

bean鏂囦欢
<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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-4.1.xsd">
    <!-- 瑁呰浇鑷瀵煎叆鐨勫寘 -->
    <context:component-scanbase-package="com.demo.spring.bean"></context:component-scan>
    <!-- 寮曞叆澶栭儴鏁版嵁婧?-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 閰嶇疆mysql鏁版嵁婧?-->
    <bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${db.driverClassName}"></property>
        <property name="url" value="${db.url}"></property>
        <property name="username" value="${db.username}"></property>
        <property name="password" value="${db.password}"></property>
    </bean>
    <!-- 閰嶇疆jdbc妯℃澘 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="datasource"></property>
    </bean>
    <!-- 閰嶇疆浜嬪姟绠$悊鍣?-->
    <bean id="transactionManagertest" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="datasource"></property>
    </bean>    
    <!-- 鍚敤浜嬪姟娉ㄨВ -->
    <tx:annotation-driven transaction-manager="transactionManagertest"/>

</beans>           
澶嶅埗

鏁版嵁婧?/h4>
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/spring
db.username=root
db.password=root           
澶嶅埗
spring事物中的传播及隔离

鐤戦棶濡備笅锛?/h4>

1銆佸墠鎻愭潯浠讹細鐢ㄦ埛鎸夌収1001锛?002杩欑椤哄簭鍘昏喘涔︼紝璋冪敤checkout鎺ュ彛鎵归噺璐功 @Transactional娉ㄨВ纭疄婊¤冻鍘熷瓙鎬ф搷浣滐紝瑕佷箞閮藉仛锛岃涔堜笉鍋?浣嗘槸锛屾垜璇曢獙浜嗕笅锛屽鏋滃湪public void checkout(String username, Listisbns) 涓婃柟涓嶅姞Transactional娉ㄨВ涓庡湪public void purchase(String username, String isbn)涓婃柟鍔燖Transactional(propagation=Propagation.REQUIRES_NEW鏁堟灉涓€鏍?

2銆佸綋璐︽埛浣欓涓?20锛屽彲浠ユ弧瓒宠处鎴峰噺鍘?001鐨勫崟浠凤紝1001鐨勫簱瀛樺噺1 浣嗘槸锛屽皢璐︽埛浣欓鏀逛负80锛屼粠鍗曚环涓婄湅鍙互涔?002閭f湰涔︼紝鎸夌収涓婇潰鐨勯『搴忓幓涔颁功锛屾寜鐓т笂闈㈠姞涓婃敞瑙Transactional(propagation=Propagation.REQUIRES_NEW鏁堟灉涓€鏍凤紝鏍规湰涓嶅ソ浣匡紝鎴戜釜浜鸿寰楀洜涓哄湪鏇存柊璐︽埛浣欓锛岄偅鏈変釜鍒ゆ柇鍏堟煡璇?001鐨勪功鐨勫崟浠风‘瀹炲ぇ浜庡綋鍓嶈处鎴蜂綑棰?0锛屽厛鍒ゆ柇浜嗭紝鎵€浠ユ姏寮傚父鍚庨潰浠g爜灏变笉璧颁簡

3銆佸彟澶栧綋鍓嶈处鎴蜂綑棰濆彲浠ヤ拱1002杩欐湰涔︼紝鎯冲湪涓嶆敼鍙樿喘涔︾殑椤哄簭鎯呭喌涓嬶紝鐢ˊTransactional娉ㄨВ瀹炵幇锛屽彲浠ヤ拱1002杩欐湰涔︼紵锛屽噺鍘诲綋鍓嶈处鎴蜂綑棰?0锛屾洿鏂?002涔︾殑搴撳瓨锛屽摢浣嶅ぇ绁炵湅鍒帮紝甯垜鐪嬩笅锛屾€庝箞鐢ㄨ繖涓敞瑙e疄鐜帮紵

浠ヤ笂涓烘垜鐨勪釜浜虹枒鎯戠殑鐐癸紝鏈夊叴瓒g殑鍚屽鍙互鐮旂┒涓嬶紝鐒跺悗鍦ㄥ叕鍙风暀瑷€缁欐垜鍗冲彲锛屽皬缂栦笉鑳滄劅璋紒

闄勪笂锛歴ql

/*
Navicat MySQL Data Transfer

Source Server         : myTestdata
Source Server Version : 50627
Source Host           : localhost:3306
Source Database       : spring

Target Server Type    : MYSQL
Target Server Version : 50627
File Encoding         : 65001

Date: 2017-01-18 11:28:50
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for account
-- ----------------------------
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
  `username` varchar(50) NOT NULL,
  `balance` int(11) DEFAULT NULL,
  PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

-- ----------------------------
-- Records of account
-- ----------------------------
INSERT INTO `account` VALUES ('rongrong', '300');
INSERT INTO `account` VALUES ('zhangsan', '200');

-- ----------------------------
-- Table structure for book
-- ----------------------------
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
  `isbn` varchar(50) NOT NULL,
  `book_name` varchar(100) DEFAULT NULL,
  `price` int(11) DEFAULT NULL,
  PRIMARY KEY (`isbn`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

-- ----------------------------
-- Records of book
-- ----------------------------
INSERT INTO `book` VALUES ('1001', 'java', '100');
INSERT INTO `book` VALUES ('1002', 'python', '60');

-- ----------------------------
-- Table structure for book_stock
-- ----------------------------
DROP TABLE IF EXISTS `book_stock`;
CREATE TABLE `book_stock` (
  `isbn` varchar(50) NOT NULL,
  `bookname` varchar(100) DEFAULT NULL,
  `stock` int(11) DEFAULT NULL,
  PRIMARY KEY (`isbn`)
) ENGINE=InnoDB DEFAULT CHARSET=gbk;

-- ----------------------------
-- Records of book_stock
-- ----------------------------
INSERT INTO `book_stock` VALUES ('1001', 'java', '10');
INSERT INTO `book_stock` VALUES ('1002', 'python', '10');           
澶嶅埗
spring事物中的传播及隔离