SpringCloud Alibaba实战
# 微服务简介
# 微服务化后的问题
一个系统,尤其是大型系统使用微服务架构模式进行搭建和开发时,虽然总体上能够提高研发效率、能够支持更高的并发,也能够提高系统整体的性能和可靠性,以及可维护性。但是在实现细节上还是存在着不少的问题。
(1)将系统拆分成各个微服务后,如果管理和感知那么多的服务呢?
(2)将系统拆分成各个微服务后,各个微服务之间如何通信?
(3)将系统拆分成各个微服务后,一旦系统出现问题,如何快速定位问题呢?
(4)将系统拆分成各个微服务后,如何最大程度的保证系统的可用性?
(5)将系统拆分成各个微服务后,客户端如何访问那么多的微服务?
# 微服务常见概念
# 服务调用
将一个系统拆分成各个微服务后,各个微服务之间协同工作才能对外提供完整的服务,这就涉及到各个微服务之间的调用问题。各个微服务之间一般会采用Restful接口或者RPC协议的方式进行调用。
(1)Restful接口
Restful接口一般是基于HTTP协议实现的,几乎所有的编程语言都支持HTTP协议。
(2)RPC协议
RPC是一种远程过程调用,能够做到像调用本地服务一样调用远程服务。RPC框架在底层屏蔽了数据的传输方式,序列化方式和交互的细节信息,让使用RPC框架使用更加简单,实现起来更加容易。
# 服务治理
说白了就是如何自动化的管理各个微服务,核心的功能就是服务的注册、发现和剔除。
(1)服务注册
各个微服务实例在启动时,能够将自身提供的服务注册到某个注册中心。
(2)服务发现
当某个微服务将自身提供的服务注册到注册中心时,其他微服务实例能够通过注册中心感知到这个微服务提供的服务,并且能够获取到这个微服务的实例信息,通过这个微服务的实例信息就能够调用这个微服务的方法,来进行相应的读写操作。
(3)服务剔除
如果某个微服务实例出现故障,或者连接一直超时,则注册中心会认为当前微服务实例不可用,就会将这个微服务实例剔除出注册中心,使其不再被其他微服务感知到和调用到。
# 注册中心
提供微服务注册、发现和剔除功能的服务组件。
# 服务网关
服务网关是所有微服务的入口,客户端在访问各个微服务时,首先需要经过服务网关。接入服务网关后,会将所有API的调用统一接入到API的网关层,由网关层统一接收参数进行路由转发,将返回的结果数据返回给客户端。
通常情况下,一个服务网关最基本的功能包括:统一接入、限流、熔断、降级、安全防护、协议适配、容错等等。主要专注的是对系统安全、流量和路由等的管理。这样,业务开发人员就可以专注于开发业务逻辑啦。
# 服务限流
在高并发大流量场景下,经常会出现某个服务或者接口因为调用的流量过大而导致不可用的情况,由于某个服务或者接口的不可用,可能还会导致整个系统崩溃。此时,就会对系统采取限流的手段来进行防护,当请求达到一定的频率或者速率时,对这些请求采取排队、等待、降级等策略,甚至是拒绝服务。
# 服务熔断
如果某个服务出现故障不可用,或者调用超时,为了不让其他服务受到牵累而导致整个系统不可用,则断开与这个服务的连接,暂停对这个服务的调用。
# 服务降级
服务降级主要是从整个系统的负载情况进行考虑,如果某些服务的负载情况比较高,则为了预防某些功能出现负载过高而导致响应慢的问题,会在提供这些功能的方法内部暂时舍弃对一些非核心功能接口的调用,直接返回一个提前准备好的错误处理信息。
服务降级是有损服务,但是能够保证整个系统的稳定性和可用性。
# 服务容错
服务容错指的是微服务能够容纳一定错误情况的发生。从某种意义上说,服务限流、服务熔断和服务降级都是服务容错的措施。
# 链路追踪
当系统被拆分成各个微服务后,一次请求往往会涉及到多个服务之间的调用关系。如果系统出现问题,则会增加定位问题的难度。为了解决这个问题,就需要对一次请求涉及到的多个服务链路的日志进行追踪和记录,一方面可以记录调用的链路,另一方面还可以监控系统中各个调用环节的性能,这就是链路追踪。
# SpringCloud Alibaba
# 主要功能
- 服务限流降级:默认支持 WebServlet、WebFlux、OpenFeign、RestTemplate、Spring Cloud Gateway、Zuul、Dubbo 和 RocketMQ 限流降级功能的接入,可以在运行时通过控制台实时修改限流降级规则,还支持查看限流降级 Metrics 监控。
- 服务注册与发现:适配 Spring Cloud 服务注册与发现标准,默认集成了 Ribbon 的支持。
- 分布式配置管理:支持分布式系统中的外部化配置,配置更改时自动刷新。
- 消息驱动能力:基于 Spring Cloud Stream 为微服务应用构建消息驱动能力。
- 分布式事务:使用 @GlobalTransactional 注解, 高效并且对业务零侵入地解决分布式事务问题。
- 阿里云对象存储:阿里云提供的海量、安全、低成本、高可靠的云存储服务。支持在任何应用、任何时间、任何地点存储和访问任意类型的数据。
- 分布式任务调度:提供秒级、精准、高可靠、高可用的定时(基于 Cron 表达式)任务调度服务。同时提供分布式的任务执行模型,如网格任务。网格任务支持海量子任务均匀分配到所有 Worker(schedulerx-client)上执行。
- 阿里云短信服务:覆盖全球的短信服务,友好、高效、智能的互联化通讯能力,帮助企业迅速搭建客户触达通道。
除了上述所具有的功能外,针对企业级用户的场景,Spring Cloud Alibaba 配套的企业版微服务治理方案 微服务引擎 MSE 还提供了企业级微服务治理中心,包括全链路灰度、服务预热、无损上下线和离群实例摘除等更多更强大的治理能力,同时还提供了企业级 Nacos 注册配置中心,企业级云原生网关等多种产品及解决方案。
# 组件
- Sentinel (opens new window) (opens new window):把流量作为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。
- Nacos (opens new window) (opens new window):一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。
- RocketMQ (opens new window) (opens new window):一款开源的分布式消息系统,基于高可用分布式集群技术,提供低延时的、高可靠的消息发布与订阅服务。
- Dubbo (opens new window) (opens new window):Apache Dubbo™ 是一款高性能 Java RPC 框架。
- Seata (opens new window) (opens new window):阿里巴巴开源产品,一个易于使用的高性能微服务分布式事务解决方案。
- Alibaba Cloud OSS (opens new window) (opens new window): 阿里云对象存储服务(Object Storage Service,简称 OSS),是阿里云提供的海量、安全、低成本、高可靠的云存储服务。您可以在任何应用、任何时间、任何地点存储和访问任意类型的数据。
- Alibaba Cloud SchedulerX (opens new window) (opens new window): 阿里中间件团队开发的一款分布式任务调度产品,提供秒级、精准、高可靠、高可用的定时(基于 Cron 表达式)任务调度服务。
- Alibaba Cloud SMS (opens new window) (opens new window): 覆盖全球的短信服务,友好、高效、智能的互联化通讯能力,帮助企业迅速搭建客户触达通道。
# 微服务环境搭建
以商城项目中的用户、商品和订单模块为例
# 项目流程设计
整个项目主要分为用户微服务、商品微服务和订单微服务,整个过程模拟的是用户下单扣减库存的操作。为了简化整个流程,将商品的库存信息保存到了商品数据表,同时,使用商品微服务来扣减库存。各服务之间的调用流程如下。
用户微服务、商品微服务和订单微服务的整体流程为:用户通过客户端调用订单微服务的提交订单的接口后,订单微服务会分别调用用户微服务和商品微服务的接口来查询用户信息和商品信息,并校验商品库存是否充足,如果商品库存充足的话,就会保存订单。并且会调用商品微服务的扣减库存的接口来扣减库存。
# 技术选型
整个项目采用SpringCloud Alibaba技术栈实现,主要的技术选型如下所示。
- 持久层框架:MyBatis、MyBatis-Plus
- 微服务框架:SpringCloud Alibaba
- 消息中间件:RocketMQ
- 服务治理与服务配置:Nacos
- 负载均衡组件:Ribbon
- 远程服务调用:Fegin
- 服务限流与容错:Sentinel
- 服务网关:SpringCloud-Gateway
- 服务链路追踪:Sleuth+ZipKin
- 分布式事务:Seata
- 数据存储:MySQL+ElasticSearch
# 模块划分
其中各模块的说明如下所示:
- mall-springcloud-alibaba:Maven父工程。
- shop-common:工具类,实体类、dto、vo等
- mall-order:订单微服务。
- mall-product:商品微服务。
- mall-user:用户微服务。
# 快速搭建三个微服务
# 用户微服务

持久层
public interface UserMapper extends BaseMapper<User> {
}
2
3
业务逻辑层
public interface UserService {
/**
* 根据id获取用户信息
*/
User getUserById(Long userId);
}
2
3
4
5
6
7
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(Long userId) {
return userMapper.selectById(userId);
}
}
2
3
4
5
6
7
8
9
10
11
接口层
@Slf4j
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping(value = "/get/{uid}")
public User getUser(@PathVariable("uid") Long uid) {
User user = userService.getUserById(uid);
log.info("获取到的用户信息为:{}", JSONObject.toJSONString(user));
return user;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
服务启动类
@SpringBootApplication
@EnableTransactionManagement(proxyTargetClass = true)
@MapperScan(value = {"cn.blazemaple.mall.user.mapper"})
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class, args);
}
}
2
3
4
5
6
7
8
9
# 商品微服务

持久层
public interface ProductMapper extends BaseMapper<Product> {
/**
* 扣减商品库存
*/
int updateProductStockById(@Param("count") Integer count, @Param("id") Long id);
}
2
3
4
5
6
7
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.blazemaple.mall.product.mapper.ProductMapper">
<update id="updateProductStockById">
update t_product
set t_pro_stock = t_pro_stock - #{count}
where id = #{id}
</update>
</mapper>
2
3
4
5
6
7
8
9
业务逻辑层
public interface ProductService {
/**
* 根据商品id获取商品信息
*/
Product getProductById(Long pid);
/**
* 扣减商品库存
*/
int updateProductStockById(Integer count, Long id);
}
2
3
4
5
6
7
8
9
10
11
12
13
@Service
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductMapper productMapper;
@Override
public Product getProductById(Long pid) {
return productMapper.selectById(pid);
}
@Override
public int updateProductStockById(Integer count, Long id) {
return productMapper.updateProductStockById(count, id);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
接口层
@RestController
@Slf4j
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping(value = "/get/{pid}")
public Product getProduct(@PathVariable("pid") Long pid){
Product product = productService.getProductById(pid);
log.info("获取到的商品信息为:{}", JSONObject.toJSONString(product));
return product;
}
@GetMapping(value = "/update_count/{pid}/{count}")
public Result<Integer> updateCount(@PathVariable("pid") Long pid, @PathVariable("count") Integer count){
log.info("更新商品库存传递的参数为: 商品id:{}, 购买数量:{} ", pid, count);
int updateCount = productService.updateProductStockById(count, pid);
Result<Integer> result = new Result<>(HttpCode.SUCCESS, "执行成功", updateCount);
return result;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
服务启动类
@SpringBootApplication
@EnableTransactionManagement(proxyTargetClass = true)
@MapperScan(value = {"cn.blazemaple.mall.product.mapper"})
public class ProductApplication {
public static void main(String[] args) {
SpringApplication.run(ProductApplication.class, args);
}
}
2
3
4
5
6
7
8
9
10
# 订单微服务

持久层
public interface OrderMapper extends BaseMapper<Order> {
}
2
3
public interface OrderItemMapper extends BaseMapper<OrderItem> {
}
2
3
业务逻辑层
public interface OrderService {
/**
* 保存订单
*/
void saveOrder(OrderParams orderParams);
}
2
3
4
5
6
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private OrderItemMapper orderItemMapper;
@Autowired
private RestTemplate restTemplate;
@Override
@Transactional(rollbackFor = Exception.class)
public void saveOrder(OrderParams orderParams) {
if (orderParams.isEmpty()) {
throw new RuntimeException("参数异常: " + JSONObject.toJSONString(orderParams));
}
User user = restTemplate.getForObject("http://localhost:8060/user/get/" + orderParams.getUserId(), User.class);
if (user == null) {
throw new RuntimeException("未获取到用户信息: " + JSONObject.toJSONString(orderParams));
}
Product product = restTemplate.getForObject("http://localhost:8070/product/get/" + orderParams.getProductId(),
Product.class);
if (product == null) {
throw new RuntimeException("未获取到商品信息: " + JSONObject.toJSONString(orderParams));
}
if (product.getProStock() < orderParams.getCount()) {
throw new RuntimeException("商品库存不足: " + JSONObject.toJSONString(orderParams));
}
Order order = new Order();
order.setAddress(user.getAddress());
order.setPhone(user.getPhone());
order.setUserId(user.getId());
order.setUsername(user.getUsername());
order.setTotalPrice(product.getProPrice().multiply(BigDecimal.valueOf(orderParams.getCount())));
orderMapper.insert(order);
OrderItem orderItem = new OrderItem();
orderItem.setNumber(orderParams.getCount());
orderItem.setOrderId(order.getId());
orderItem.setProId(product.getId());
orderItem.setProName(product.getProName());
orderItem.setProPrice(product.getProPrice());
orderItemMapper.insert(orderItem);
Result<Integer> result = restTemplate.getForObject(
"http://localhost:8070/product/update_count/" + orderParams.getProductId() + "/" + orderParams.getCount(),
Result.class);
if (result.getCode() != HttpCode.SUCCESS) {
throw new RuntimeException("库存扣减失败");
}
log.info("库存扣减成功");
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
接口层
@RestController
@Slf4j
public class OrderController {
@Autowired
private OrderService orderService;
@GetMapping(value = "/submit_order")
public String submitOrder(OrderParams orderParams) {
log.info("提交订单时传递的参数:{}", JSONObject.toJSONString(orderParams));
orderService.saveOrder(orderParams);
return "success";
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
由于使用了RestTemplate来完成远程服务的调用,新建LoadBalanceConfig类,在LoadBalanceConfig类中使用@Bean注解将RestTemplate对象交由Spring管理
@Configuration
public class LoadBalanceConfig {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
2
3
4
5
6
7
8
服务启动类
@SpringBootApplication
@EnableTransactionManagement(proxyTargetClass = true)
@MapperScan(value = {"cn.blazemaple.mall.order.mapper"})
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
2
3
4
5
6
7
8
9
10
# 数据库
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for t_order
-- ----------------------------
DROP TABLE IF EXISTS `t_order`;
CREATE TABLE `t_order` (
`id` bigint NOT NULL,
`t_user_id` bigint NOT NULL,
`t_user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`t_phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`t_address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`t_total_price` decimal(10, 4) NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for t_order_item
-- ----------------------------
DROP TABLE IF EXISTS `t_order_item`;
CREATE TABLE `t_order_item` (
`id` bigint NOT NULL,
`t_order_id` bigint NULL DEFAULT NULL,
`t_pro_id` bigint NULL DEFAULT NULL,
`t_pro_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`t_pro_price` decimal(10, 3) NULL DEFAULT NULL,
`t_number` int NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for t_product
-- ----------------------------
DROP TABLE IF EXISTS `t_product`;
CREATE TABLE `t_product` (
`id` bigint NOT NULL,
`t_pro_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`t_pro_price` decimal(10, 3) NULL DEFAULT NULL,
`t_pro_stock` int NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of t_product
-- ----------------------------
INSERT INTO `t_product` VALUES (1001, '华为', 2399.000, 100);
INSERT INTO `t_product` VALUES (1002, '小米', 1999.000, 100);
INSERT INTO `t_product` VALUES (1003, 'iphone', 4999.000, 100);
-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` bigint NOT NULL,
`t_username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`t_password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`t_phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`t_address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES (1001, 'bm', 'c26be8aaf53b15054896983b43eb6a65', '13212345678', '北京');
SET FOREIGN_KEY_CHECKS = 1;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69