Spring Cloud的分布式事务组件

今天我学习了Spring Cloud的分布式事务组件:Spring Cloud Alibaba SeataSpring 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特性。

posted @   ITJAMESKING  阅读(41)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示