Spring事务

分布式项目总会面临分布式事务的问题。公司的项目中有多个子系统用户同步信息的问题。最近要研究解决一下出现分布式事务时候的解决办法。把学习的过程记录一下

Spring事务管理的特点

  • 提供的统一的API接口 支持不同的资源
  • 提供声明式 事务管理
  • 方便与spring框架集成
  • 多个资源的事务的管理 同步

Spring抽象事务

  • PlatformTranscationManager
  • TranscationStatus
  • TranscationDefinition
Public interface TranscationDefinition(){
int getPropagation Behavior();
int getIsolationLevel();
String getName();
int getTimeOut();
boolean isReadOnly();
}
public interface TranscationStatus extends SavepointManager{
boolean isNewTransaction();
boolean hasSavepoint();
void setRollbackOnly();
boolean isRollbackOnly();
boolean isCompleted();
}

启用spring事务可以通过代码的方式 也可以通过注解的方式,在自己的项目中 我用注解的方式更多一些 主要就是简单 不需要写那么的代码 而注解完成事务及回滚也是通过代理的方式来完成的。在本地的测试中 使用springboot + h2数据库+jpa的方式 这样会方便一点

jpa在自己写的实际项目中 用的比较少 但是确实是更方便了一点 不需要再xml文件中 进行对应 只要在实体类中 通过@Entity @column 这种方式 来进行对应 而且对于dao层 mybatis的dao层 需要一个实现类

而在jpa中 实现是通过 repository 从名字可以看出来 仓库 在其中 会有很多增删改差的方法 直接调用就可以 不需要自己在实现类中写了

测试的代码参考了慕课网上大漠风老师课程中思路

service中的方法 是使用了通过代码和通过注解两种方式

domain 类
package com.emp.transcationjap.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 * Created with IntelliJ IDEA.
 * User: employeeeee
 * Date: 2019/5/13
 * Time: 16:15
 * Description: No Description
 */
@Entity(name = "customer")
public class Customer {
    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "user_name", length = 6)
    private String username;

    private String password;

    private String role;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }
}

dao层Repository
package com.emp.transcationjap.dao;

import com.emp.transcationjap.domain.Customer;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * Created with IntelliJ IDEA.
 * User: employeeeee
 * Date: 2019/5/13
 * Time: 16:17
 * Description: No Description
 */
public interface CustomerRepository extends JpaRepository<Customer,Long> {

}
两个service
package com.emp.transcationjap.service;

import com.emp.transcationjap.dao.CustomerRepository;
import com.emp.transcationjap.domain.Customer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: employeeeee
 * Date: 2019/5/13
 * Time: 16:21
 * Description: No Description
 */
@Service
public class CustomerServiceTcInAnnotation {
    @Resource
    CustomerRepository customerRepository;

    @Transactional
    public Customer save(Customer customer) throws Exception{
       return customerRepository.save(customer);
    }

    public List<Customer> saveAll(List<Customer> customerList) throws Exception{
        return customerRepository.saveAll(customerList);
    }

}

package com.emp.transcationjap.service;

import com.emp.transcationjap.dao.CustomerRepository;
import com.emp.transcationjap.domain.Customer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;

/**
 * Created with IntelliJ IDEA.
 * User: employeeeee
 * Date: 2019/5/13
 * Time: 16:21
 * Description: No Description
 */
@Service
public class CustomerServiceTcInCode {
    @Resource
    private CustomerRepository customerRepository;
    @Resource
    private PlatformTransactionManager  transactionManager;

    public Customer save(Customer customer) {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        //隔离机制 所有的操作都会进行排队 对性能的影响比较大
        def.setIsolationLevel(DefaultTransactionDefinition.ISOLATION_SERIALIZABLE);
        //传播机制
        def.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_SUPPORTS);
        def.setTimeout(15);
        TransactionStatus status = transactionManager.getTransaction(def);
        try{
            customerRepository.save(customer);
            return customer;
        }catch (Exception e){
            transactionManager.rollback(status);
            throw e;
        }
    }
}

controller
package com.emp.transcationjap.web;

import com.emp.transcationjap.dao.CustomerRepository;
import com.emp.transcationjap.domain.Customer;
import com.emp.transcationjap.service.CustomerServiceTcInAnnotation;
import com.emp.transcationjap.service.CustomerServiceTcInCode;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: employeeeee
 * Date: 2019/5/13
 * Time: 16:55
 * Description: No Description
 */
@RestController
@RequestMapping("/test")
public class CustomerController {
    @Resource
    private CustomerServiceTcInAnnotation customerServiceTcInAnnotation;

    @Resource
    private CustomerServiceTcInCode customerServiceTcInCode;

    @Resource
    private  CustomerRepository customerRepository;

    @RequestMapping("/code")
    public void saveInCode(Customer customer){
        customer.setId(1001L);
        customer.setUsername("zhou");
        customer.setPassword("123456");
        customer.setRole("user");
        customerServiceTcInCode.save(customer);
    }

    @RequestMapping("/anno")
    public void saveInAnno(Customer customer) throws Exception {
        customer.setId(1002L);
        customer.setUsername("KrisW");
        customer.setPassword("123456");
        customer.setRole("user");
        customerServiceTcInAnnotation.save(customer);
    }

    @RequestMapping("/saveAll")
    @Transactional
    public void saveAll() throws Exception {

        Customer customer1 = new Customer();
        customer1.setId(1003L);
        customer1.setUsername("kunkun");
        customer1.setPassword("123456");
        customer1.setRole("user");

        Customer customer2 = new Customer();
        customer2.setId(1004L);
        customer2.setUsername("liu");
        customer2.setPassword("123456");
        customer2.setRole("user");


        Customer customer3 = new Customer();
        customer3.setId(1005L);
        customer3.setUsername("KrisWuuuuu");
        customer3.setPassword("123456");
        customer3.setRole("user");

        customerServiceTcInCode.save(customer1);
        customerServiceTcInCode.save(customer2);
        customerServiceTcInCode.save(customer3);
    }

    @RequestMapping("/getAll")
    public List<Customer> getAll(){
        List<Customer> customerList = customerRepository.findAll();
        return customerList;
    }

}

然后就在web上进行 测试就OK了
那么有了事务 和 没有事务的区别是什么呢
就是在saveAll的方法中
我让第三个用户的名字超出了 length为6的限制 所以就会报错
然后查询出来的结果 会是这样的


image.png

也就是说 虽然项目报错了 但是前两条数据还是已经加入到了数据库中 这样显然不是我们想要的效果 当我们加上事务时候
就会出现回滚 也就是前两条数据 就不会被添加到数据库中了

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,907评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,987评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,298评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,586评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,633评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,488评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,275评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,176评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,619评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,819评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,932评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,655评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,265评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,871评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,994评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,095评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,884评论 2 354

推荐阅读更多精彩内容