Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

事务问题 #12

Open
PrimaryKey3610 opened this issue Jan 19, 2024 · 1 comment
Open

事务问题 #12

PrimaryKey3610 opened this issue Jan 19, 2024 · 1 comment

Comments

@PrimaryKey3610
Copy link

/**
* 执行操作(带自定义的失败处理),并根据操作是否成功返回给客户端相应信息
* 封装了在服务端接口中很常见的执行操作,成功返回成功标志、失败返回失败标志的通用操作,用于简化编码
*/
public static Response op(Runnable executor, Consumer exceptionConsumer) {
try {
executor.run();
return CommonResponse.success();
} catch (Exception e) {
exceptionConsumer.accept(e);
return CommonResponse.failure(e.getMessage());
}
}

您这边使用线程执行service逻辑,
1、 首先方法会在try中执行,spring事务在执行回滚时,是捕捉运行时异常才会生效,您这样写,我不太理解
2、其次您这个方法类似于多线程执行,但是spring事务默认是在主线程中执行,没有实现跨线程,这样的代码不确定是否生效

@m1stake
Copy link

m1stake commented Jun 26, 2024

  1. 事务声明在 Service 层(@transactional),如果有异常的话,执行到这里,事务其实已经回滚了。
    你可以认为 executor.run(); 相当于下面的代码(只是说明事务的问题)
try {
    userService.createAccount();
} catch (RuntimeException e) {
    transaction.rollback();
    throw e;
}
  1. Runnable 和线程的绑定关系只是 Java8 之前。Java8 之后 Runnable 很多时候也会被用于函数式编程,这里就是用于函数式编程。Runnable 只是一个接口,和线程并没有直接的关系。Thread 才是真正实现线程功能的类。
Runnable runnable = new Runnable() {
    public void run() {
        System.out.println("Run ... ");
    }
};
// Runnable runnable1 = () -> System.out.println("Run1 ... "); 
runnable.run();  // 这里就会直接执行,并没有新的线程产生,和一般的接口没有任何区别

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants