Spring Cloud的分布式事务组件
今天我学习了Spring Cloud的分布式事务组件:Spring Cloud Alibaba Seata。Spring Cloud Alibaba Seata是一种分布式事务管理框架,能够实现分布式事务的ACID特性。下面是一个使用Spring Cloud Alibaba Seata的示例:
@SpringBootApplication
@EnableDiscoveryClient
@MapperScan("com.example.demo.dao")
@EnableAutoDataSourceProxy
@EnableFeignClients(basePackages = "com.example.demo.service.feign")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@RestController
class HelloController {
@Autowired
private HelloService helloService;
@GetMapping("/hello")
public String hello() {
return helloService.hello();
}
}
@Service
@FeignClient("demo-service-provider")
interface HelloService {
@GetMapping("/hello")
String hello();
}
@Service
public class HelloServiceImpl implements HelloService {
@Autowired
private HelloMapper helloMapper;
@Override
@GlobalTransactional
public String hello() {
helloMapper.insert(new Hello(1L, "Hello, world!"));
return "Hello, world!";
}
}
@Mapper
public interface HelloMapper {
@Insert("insert into hello(id, message) values(#{id}, #{message})")
int insert(Hello hello);
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Hello {
private Long id;
private String message;
}
这个示例中,我们使用@EnableAutoDataSourceProxy注解将数据源代理给Seata,使用@EnableFeignClients注解创建一个FeignClient实例,使用@GlobalTransactional注解标记服务的入口方法,从而实现分布式事务的ACID特性。


浙公网安备 33010602011771号