事务同步器

2024-06-26

java

君子择交,莫恶于易与,莫善于胜己。——王夫之

有时候我们需要在事务执行前后执行一些代码,这时候可以使用事务同步器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import org.springframework.transaction.support.TransactionSynchronization;

public class MyTransactionSynchronization implements TransactionSynchronization {

@Override
public void beforeCommit(boolean readOnly) {
// 事务提交之前的逻辑
System.out.println("Before commit");
}

@Override
public void beforeCompletion() {
// 事务完成之前的逻辑
System.out.println("Before completion");
}

@Override
public void afterCommit() {
// 事务成功提交之后的逻辑
System.out.println("After commit");
}

@Override
public void afterCompletion(int status) {
// 事务完成之后的逻辑
if (status == STATUS_COMMITTED) {
System.out.println("Transaction committed");
} else if (status == STATUS_ROLLED_BACK) {
System.out.println("Transaction rolled back");
}
}
}

注册事务同步器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api")
public class MyController {

@GetMapping("/test")
public String test() {
// 检查当前事务是否已经注册了该同步器
List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager.getSynchronizations();
boolean alreadyRegistered = synchronizations.stream()
.anyMatch(sync -> sync instanceof MyTransactionSynchronization);

if (!alreadyRegistered) {
// 只在未注册时注册新的事务同步器
TransactionSynchronizationManager.registerSynchronization(new MyTransactionSynchronization());
}

// 执行其他逻辑
return "Test completed";
}
}

class MyTransactionSynchronization implements TransactionSynchronization {
@Override
public void afterCompletion(int status) {
if (status == STATUS_COMMITTED) {
System.out.println("Transaction committed");
} else {
System.out.println("Transaction rolled back");
}
}

@Override
public void beforeCommit(boolean readOnly) {
System.out.println("Before commit");
}

@Override
public void beforeCompletion() {
System.out.println("Before completion");
}

@Override
public void afterCommit() {
System.out.println("After commit");
}
}