springboot + springcloud alibaba seata 使用TCC模式代码模板
时间: 2023-11-18 21:06:16 浏览: 162
以下是一个使用Spring Boot和Spring Cloud Alibaba Seata框架实现的TCC模式代码模板:
1. 创建一个Spring Boot项目,添加依赖:
```xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
```
2. 配置Seata相关信息:
```yaml
spring:
application:
name: tcc-demo
seata:
enabled: true
application-id: ${spring.application.name}
tx-service-group: my_tx_group
service:
vgroup-mapping.my_tx_group: default
config:
type: nacos
nacos:
server-addr: localhost:8848
namespace: public
registry:
type: nacos
nacos:
server-addr: localhost:8848
namespace: public
storage:
type: db
db:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/seata?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: root
```
3. 创建一个TCC接口:
```java
public interface TccService {
@TccTransaction(confirmMethod = "confirm", cancelMethod = "cancel")
boolean tryMethod(String businessKey, String param);
boolean confirm(String businessKey, String param);
boolean cancel(String businessKey, String param);
}
```
4. 实现TCC接口:
```java
@Service
public class TccServiceImpl implements TccService {
@Resource
private TccMapper tccMapper;
@Override
public boolean tryMethod(String businessKey, String param) {
TccEntity tccEntity = new TccEntity();
tccEntity.setBusinessKey(businessKey);
tccEntity.setParam(param);
return tccMapper.insert(tccEntity) > 0;
}
@Override
public boolean confirm(String businessKey, String param) {
return true;
}
@Override
public boolean cancel(String businessKey, String param) {
return tccMapper.deleteByBusinessKey(businessKey) > 0;
}
}
```
5. 配置TCC事务管理器:
```java
@Configuration
public class SeataConfiguration {
@Bean
public GlobalTransactionScanner globalTransactionScanner() {
return new GlobalTransactionScanner("tcc-demo", "my_tx_group");
}
@Bean
public TccTransactionAspect tccTransactionAspect() {
return new TccTransactionAspect();
}
@Bean
public DataSourceProxy dataSourceProxy(DataSource dataSource) {
return new DataSourceProxy(dataSource);
}
}
```
6. 测试TCC接口:
```java
@RestController
@RequestMapping("/tcc")
public class TccController {
@Resource
private TccService tccService;
@PostMapping("/try")
public boolean tryMethod(@RequestParam String businessKey, @RequestParam String param) {
return tccService.tryMethod(businessKey, param);
}
}
```
以上是一个简单的TCC模式代码模板,可以根据实际业务需求进行修改和扩展。
阅读全文