IT序号网

SpringCloud AlibabaSeata1.5.2的安装

itxm 2023年04月30日 程序员 550 0

1. 下载Seata1.5.2

从Seata官网下载Seata1.5.2的压缩包,解压到本地。

2. 配置Seata Server

进入解压后的Seata目录,进入conf目录,修改file.conf文件,配置Seata Server的存储方式和数据库连接信息。

bash 
store { 
  mode = "db" 
  db { 
    driverClassName = "com.mysql.jdbc.Driver" 
    url = "jdbc:mysql://localhost:3306/seata" 
    user = "root" 
    password = "root" 
  } 
} 

3. 配置注册中心

Seata Server需要注册到注册中心,这里以Nacos为例。修改registry.conf文件,配置Nacos的地址和命名空间。

bash 
registry { 
  type = "nacos" 
  nacos { 
    serverAddr = "localhost:8848" 
    namespace = "" 
    cluster = "default" 
  } 
} 

4. 启动Seata Server

进入bin目录,执行以下命令启动Seata Server。

bash 
sh seata-server.sh -p 8091 -h 127.0.0.1 -m file 

其中,-p参数指定Seata Server的端口号,-h参数指定Seata Server的IP地址,-m参数指定Seata Server的存储方式。

5. 集成Seata

在SpringCloud项目中集成Seata,需要引入以下依赖。

xml 

   
    
   
    io.seata
    
    
   
    seata-all
    
    
   
    1.5.2
    

   

在SpringCloud项目的配置文件中,配置Seata的注册中心和事务组名称。

yaml 
spring: 
  cloud: 
    alibaba: 
      seata: 
        tx-service-group: my_tx_group 
        service: 
          group: my_group 
          name: ${spring.application.name} 
          registry-type: nacos 
          nacos: 
            server-addr: localhost:8848 
            namespace:  
            cluster-name: default 

在需要进行分布式事务的方法上,添加@GlobalTransactional注解。

java 
@Service 
public class OrderServiceImpl implements OrderService { 
 
    @Autowired 
    private OrderMapper orderMapper; 
 
    @Autowired 
    private StorageService storageService; 
 
    @Autowired 
    private AccountService accountService; 
 
    @Override 
    @GlobalTransactional 
    public void create(Order order) { 
        // 扣减库存 
        storageService.decrease(order.getProductId(), order.getCount()); 
        // 扣减账户余额 
        accountService.decrease(order.getUserId(), order.getMoney()); 
        // 创建订单 
        orderMapper.create(order); 
    } 
} 

6. 测试Seata

启动SpringCloud项目,调用分布式事务方法,观察Seata Server的日志输出,确认分布式事务是否成功。

参考资料:

- Seata官网:https://seata.io/

- SpringCloud Alibaba官网:https://spring.io/projects/spring-cloud-alibaba


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!