手写Spring事务管理,全部自己手写代码,亲测可用,大家不懂的地方可以经过断点一步步分析

1.程序运行类:

public class TestMain {
    public static void main(String[] args) {
//        UserService userService = new UserServiceImpl();
//        UserDaoProxy userDaoProxy = new UserDaoProxy(userService);
//        userDaoProxy.add();
//        UserService o = (UserService)InvocationHandlerImpl.ClassLoader(new UserServiceImpl());
//        o.add();
        //使用ClassPathXmlApplicationContext 加载spring.xml文件
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("spring.xml");
        //调用需要执行的方法
        UserService userService = (UserService) classPathXmlApplicationContext.getBean("userServiceImpl");
        userService.add();
    }
}

2.AOP事务切面类:

将一些复用的代码块,使用AOP封装,保持代码的整洁,事务通知,不一一介绍

//切面类
@Aspect
@Component
public class AopLog {
    //前置通知
    @Before("execution(* com.shty.springtransaction.service..*.*(..))")
    public void before(){
        System.out.println("前置通知,在方法之前执行....");
    }
    // 运行通知
    @AfterReturning("execution(* com.shty.springtransaction.service..*.*(..))")
    public void returning() {
        System.out.println("运行通知.....");
    }

    //后置通知
    @After("execution(* com.shty.springtransaction.service..*.*(..))")
    public void after(){
        System.out.println("后置通知,在方法之后执行....");
    }
}

3.AOP手动封装事务

环绕通知:得到请求的方法,保持事务出现异常,不会调用后面的代码。

异常通知:保证项目出现异常,异常通知可以获取到,则将当前事务进行回滚。

//aop 手动事务封装
@Component
@Aspect
public class AopTransactionUtils {

    @Autowired
    private transactionUtils transactionUtils;

    // 环绕通知
    @Around("execution(* com.shty.springtransaction.service..*.*(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕通知开始....开启事务");
        TransactionStatus begin = transactionUtils.begin();
        //调用方法,如果调用方法抛出异常,不会执行后面的代码
        proceedingJoinPoint.proceed();
        System.out.println("环绕通知结束.....提交事务");
        transactionUtils.commit(begin);
    }

    // 异常通知
    @AfterThrowing("execution(* com.shty.springtransaction.service..*.*(..))")
    public void afterThrowing() {
        System.out.println("异常通知....回滚事务");
        //获取当前事务 直接回滚
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    }

4.service   与serviceImpl类

public interface UserService {
    public void add();
}



@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

 public void add() {
        //注意:在使用Spring事务的时候,service不需要try 将异常抛出给aop 异常通知接受回滚,如果要try 手动进行回滚。
       // try {
            System.out.println("往数据库添加数据");
       //     int i = 1/0;
            userDao.add("test",18);
        //}catch (Exception e){
            //手动进行回滚
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        //}
    }
}

5.dao类,插入数据库方法

@Repository
public class UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void add(String name, Integer age) {
        String sql = "INSERT INTO user(NAME, age) VALUES(?,?);";
        int updateResult = jdbcTemplate.update(sql, name, age);
        System.out.println("updateResult:" + updateResult);
    }

6.spring.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:p="http://www.springframework.org/schema/p"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

	<context:component-scan base-package="com.shty"></context:component-scan>
	<aop:aspectj-autoproxy></aop:aspectj-autoproxy> <!-- 开启事物注解 -->

	<!-- 1. 数据源对象: C3P0连接池 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
		<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
		<property name="user" value="root"></property>
		<property name="password" value="123456"></property>
	</bean>

	<!-- 2. JdbcTemplate工具类实例 -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>

	<!-- 3.配置事务 -->
	<bean id="dataSourceTransactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
</beans>

7.pom.xml文件

<dependencies>
		<!-- 引入Spring-AOP等相关Jar -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.0.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.0.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>3.0.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>3.0.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.6.1</version>
		</dependency>
		<dependency>
			<groupId>aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.5.3</version>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.1_2</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
		<dependency>
			<groupId>com.mchange</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.5.2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.37</version>
		</dependency>
	</dependencies>

 

RPC(Remote Procedure Call)是一种进程间通信方式,用于实现分布式系统中的服务调用。在分布式系统中,由于各个服务之间的相互依赖和调用,往往需要对这些调用进行事务管理,以保证数据的一致性和完整性。下面我们将介绍如何手写一个简单的分布式事务管理器,并生成相应的代码示例。 首先,我们需要定义事务管理器中的一些基本概念: - 事务:一组操作的集合,要么全部执行成功,要么全部回滚。 - 事务管理器:负责事务的管理和协调,包括事务的开始、提交、回滚等操作。 - 事务参与者:参与事务的各个服务,需要将其所执行的操作注册到事务管理器中。 接下来,我们可以考虑如何实现一个简单的分布式事务管理器。为了简化实现,我们可以采用两阶段提交协议(Two-Phase Commit Protocol)。该协议包括以下两个阶段: - 预提交阶段(Prepare Phase):事务管理器向所有事务参与者发送预提交请求,并等待所有参与者的响应。如果所有参与者都能正常响应,则事务管理器会向所有参与者发送提交请求;否则,事务管理器会向所有参与者发送回滚请求。 - 提交/回滚阶段(Commit/Rollback Phase):事务管理器向所有参与者发送提交或回滚请求,并等待所有参与者的响应。如果所有参与者能正常响应,则事务提交成功;否则,事务回滚。 下面是一个简单的分布式事务管理器的代码示例: ```python import rpc class TransactionManager: def __init__(self): self.participants = [] self.transaction_id = 0 def begin(self): self.transaction_id += 1 return self.transaction_id def register_participant(self, participant): self.participants.append(participant) def prepare(self, transaction_id): for participant in self.participants: participant.prepare(transaction_id) # 等待所有参与者的响应 responses = [] for participant in self.participants: response = participant.get_response() responses.append(response) # 判断是否要提交或回滚 if all(responses): self.commit(transaction_id) else: self.rollback(transaction_id) def commit(self, transaction_id): for participant in self.participants: participant.commit(transaction_id) def rollback(self, transaction_id): for participant in self.participants: participant.rollback(transaction_id) class TransactionParticipant: def __init__(self, address): self.address = address self.response = False def prepare(self, transaction_id): rpc.call(self.address, 'prepare', transaction_id) def commit(self, transaction_id): rpc.call(self.address, 'commit', transaction_id) def rollback(self, transaction_id): rpc.call(self.address, 'rollback', transaction_id) def get_response(self): return self.response def set_response(self, response): self.response = response ``` 在上面的代码中,我们定义了一个 `TransactionManager` 类和一个 `TransactionParticipant` 类。`TransactionManager` 类负责管理事务,包括开始事务、注册参与者、预提交、提交和回滚等操作。`TransactionParticipant` 类代表事务参与者,包括预提交、提交和回滚等操作。 在 `TransactionManager` 类中,我们使用了 `rpc` 模块来实现远程过程调用。在 `prepare` 方法中,我们向所有参与者发送预提交请求,并等待所有参与者响应。如果所有参与者都能响应,则向所有参与者发送提交请求;否则,向所有参与者发送回滚请求。 在 `TransactionParticipant` 类中,我们也使用了 `rpc` 模块来实现远程过程调用。在 `prepare` 方法中,我们将自己的事务操作注册到事务管理器中,并等待事务管理器的响应。在 `commit` 和 `rollback` 方法中,我们向事务管理器发送提交或回滚请求。 总之,以上是一个简单的分布式事务管理器的代码示例。在实际应用中,需要根据实际情况进行相应的调整和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值