
- 20 SpringCloud Alibabaseata处理分布式事务
- 20.1 Seata简介
- 20.2 Seata-Server安装
- 20.3 微服务表的创建
- 20.4 订单/库存/账户业务微服务准备
- 20.5 测试
最后一个组件 也是最重要的 进行微服务之间的事务管理的组件 20 SpringCloud Alibabaseata处理分布式事务
我们知道 有时候一个微服务可能会调用其他的微服务
但是当我们进行服务调用的时候 有可能会出现 异常
但是 如果我们没有合理的管理事务 那么就可能造成一部分成功 一部分失败
就会导致数据不一致 这是一个很要命的问题
怎么解决呢?
简单一句话 就是在我们需要添加 事务的地方 加上一个@GlobalTransactional注解即可
但是其中的配置 有点多
20.1 Seata简介Seata是一款开源的分布式事务解决方案,致力于在微服务架构下提供高性能和简单易用的分布式事务服务。
官方下载地址
https://github.com/seata/seata/releases
怎么用?
修改的详细内容 会在之后发出的脑图中进行详细说明
然后启动seata即可
过后我们在mysql创建新的数据库 seata
创建好数据库过后创建表 建表db_store.sql在seata-server-0.9.0seataconf目录里面
然后修改seata-server-0.9.0seataconf目录下的registry.conf配置文件
先启动nacos 再启动seata
这个微服务的 过程如下
下订单—>扣库存—>减账户(余额)
新建一个订单模块 seata-order-service2001
com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discoverycom.alibaba.cloud spring-cloud-starter-alibaba-seataseata-all io.seata io.seata seata-all0.9.0 org.springframework.cloud spring-cloud-starter-openfeignorg.springframework.boot spring-boot-starter-weborg.springframework.boot spring-boot-starter-actuatormysql mysql-connector-java5.1.37 com.alibaba druid-spring-boot-starter1.1.10 org.mybatis.spring.boot mybatis-spring-boot-starter2.0.0 org.springframework.boot spring-boot-starter-testtest org.projectlombok lomboktrue
yaml
server:
port: 2001
spring:
application:
name: seata-order-service
cloud:
alibaba:
seata:
#自定义事务组名称需要与seata-server中的对应
tx-service-group: fsp_tx_group
nacos:
discovery:
server-addr: localhost:8848
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/seata_order
username: root
password: 123456
feign:
hystrix:
enabled: false
logging:
level:
io:
seata: info #打开seata
mybatis:
mapperLocations: classpath:mapper/*.xml
因为这里 用了seata 所以需要在项目的resource资源目录创建两个文件
file.conf 和 registry.conf 对应的文件内容 可以在脑图里面查看
然后就是两个bean
CommonResult 用于返回的格式设置
@Data @AllArgsConstructor @NoArgsConstructor public class CommonResult{ private Integer code; private String message; private T data; public CommonResult(Integer code, String message) { this(code,message,null); } }
Order 对应的数据库表的实体
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Order
{
private Long id;
private Long userId;
private Long productId;
private Integer count;
private BigDecimal money;
private Integer status;
}
然后就编写一个Dao 实现订单的更改
@Mapper
public interface OrderDao {
void create(Order order);
void update(@Param("userId") Long userId, @Param("status") Integer status);
}
不要忘记在resource/mapper目录下创建 OrderMapper.XML文件并进行对应的配置
INSERT INTO `t_order` (`id`, `user_id`, `product_id`, `count`, `money`, `status`) VALUES (NULL, #{userId}, #{productId}, #{count}, #{money}, 0); UPDATE `t_order` SET status = 1 WHERe user_id = #{userId} AND status = #{status};
service层用的openfeign的服务调用
OrderService类
public interface OrderService {
void create(Order order);
}
实现类
@Service
@Slf4j
public class OrderServiceImpl implements OrderService
{
@Resource
private OrderDao orderDao;
@Resource
private StorageService storageService;
@Resource
private AccountService accountService;
@Override
@GlobalTransactional(name = "fsp-create-order",rollbackFor = Exception.class)
public void create(Order order) {
log.info("------->下单开始");
//本应用创建订单
orderDao.create(order);
//远程调用库存服务扣减库存
log.info("------->order-service中扣减库存开始");
storageService.decrease(order.getProductId(),order.getCount());
log.info("------->order-service中扣减库存结束");
//远程调用账户服务扣减余额
log.info("------->order-service中扣减余额开始");
accountService.decrease(order.getUserId(),order.getMoney());
log.info("------->order-service中扣减余额结束");
//修改订单状态为已完成
log.info("------->order-service中修改订单状态开始");
orderDao.update(order.getUserId(),0);
log.info("------->order-service中修改订单状态结束");
log.info("------->下单结束");
}
}
然后就是两个根据openfeig调用的接口
StorageService
@FeignClient(value = "seata-storage-service")
public interface StorageService {
@PostMapping(value = "/storage/decrease")
CommonResult decrease(@RequestParam("productId") Long productId, @RequestParam("count") Integer count);
}
AccountService
@FeignClient(value = "seata-account-service")
public interface AccountService {
//@RequestMapping(value = "/account/decrease", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
@PostMapping("/account/decrease")
CommonResult decrease(@RequestParam("userId") Long userId, @RequestParam("money") BigDecimal money);
}
简单的controller层
@RestController
public class OrderController {
@Autowired
private OrderService orderService;
@GetMapping("/order/create")
public CommonResult create( Order order) {
orderService.create(order);
return new CommonResult(200, "订单创建成功!");
}
}
在这里还需要两个配置类
@Configuration
@MapperScan({"com.atguigu.springcloud.alibaba.dao"})
public class MyBatisConfig {
}
@Configuration
public class DataSourceProxyConfig {
@Value("${mybatis.mapperLocations}")
private String mapperLocations;
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource(){
return new DruidDataSource();
}
@Bean
public DataSourceProxy dataSourceProxy(DataSource dataSource) {
return new DataSourceProxy(dataSource);
}
@Bean
public SqlSessionFactory sqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSourceProxy);
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
return sqlSessionFactoryBean.getObject();
}
}
最后就是主启动类 这里用了fegin 不要忘记加上EnableFeignClients注解
@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//取消数据源的自动创建
public class SeataOrderMainApp2001
{
public static void main(String[] args)
{
SpringApplication.run(SeataOrderMainApp2001.class, args);
}
}
其余两个模块 大同小异 其实想用这个微服务事物管理 最主要的就是 两个在resource创建的两个*.config文件
其他两个模块参考这个模块即可完成
最后三个模块总体图如下
Order
Storage
Account
当我们在没有实现服务管理的情况跟下 就会出现数据错误
那么在这个时候 我们需要在 OrderServiceImpl 层的 create添加上 @GlobalTransactional注解
//name 表示这个事物在哪个组里面 rollbackFor 表示需要回滚的方法
@GlobalTransactional(name = "fsp-create-order",rollbackFor = Exception.class)
public void create(Order order)
{
}
当我们再次出错 时就可以 完美回滚了
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)