本博客面向具有一定 Spring Boot 和微服务基础 的开发者,旨在深入讲解 Spring Cloud Alibaba 核心组件 的使用与配置方法。我们将围绕以下三个核心组件展开详细说明:
通过实际的代码示例和项目案例,帮助你快速上手并掌握这些组件在微服务架构中的应用。
Spring Cloud Alibaba 是阿里巴巴开源技术与 Spring Cloud 的集成框架,它为国内微服务开发提供了更符合本地化需求的解决方案。
组件名 | 功能描述 |
---|---|
Nacos | 注册中心 + 配置中心 |
Sentinel | 流量控制、熔断降级 |
Gateway | 基于 WebFlux 的 API 网关 |
Seata | 分布式事务管理 |
本博客重点介绍 Sentinel、Gateway、Seata。
Sentinel 是阿里巴巴开源的轻量级高可用流量控制组件,支持限流、熔断、系统保护等功能。
# 下载地址(以最新版本为例):
https://github.com/alibaba/Sentinel/releases
# 启动 Dashboard
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.8.6.jar
访问 http://localhost:8080
登录,默认账号密码均为 sentinel
。
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
<version>2022.0.0.0version>
dependency>
# application.yml
server:
port: 8081
spring:
application:
name: demo-service
cloud:
sentinel:
transport:
dashboard: localhost:8080
// 示例 Controller
@RestController
public class DemoController {
@GetMapping("/hello")
@SentinelResource(value = "hello", fallback = "fallbackHello")
public String hello() {
return "Hello, Sentinel!";
}
public String fallbackHello(Throwable t) {
return "服务繁忙,请稍后再试:" + t.getMessage();
}
}
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.util.TimeUtil;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class SentinelConfig {
@PostConstruct
public void initFlowRules() {
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule();
rule.setResource("hello"); // 对应 @SentinelResource 的 value
rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 按 QPS 限流
rule.setCount(2); // 每秒最多允许2次请求
rules.add(rule);
FlowRuleManager.loadRules(rules);
}
}
Spring Cloud Gateway 是基于 Reactor Netty 构建的非阻塞网关,支持动态路由、限流、熔断等功能。
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-gatewayartifactId>
dependency>
# application.yml
server:
port: 8080
spring:
cloud:
gateway:
routes:
- id: order-service
uri: lb://order-service
predicates:
- Path=/api/order/**
filters:
- StripPrefix=1
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
System.out.println("前置处理逻辑...");
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
System.out.println("后置处理逻辑...");
}));
}
@Override
public int getOrder() {
return 0; // 过滤器执行顺序
}
}
# application.yml
spring:
cloud:
gateway:
routes:
- id: rate-limit-route
uri: lb://user-service
predicates:
- Path=/api/user/**
filters:
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 1
redis-rate-limiter.burstCapacity: 3
key-resolver: "#{@userKeyResolver}"
@Bean
KeyResolver userKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("userId"));
}
Seata 是一款开源的高性能分布式事务解决方案,支持 AT、TCC、SAGA、XA 等模式。
# 下载并启动
unzip seata-server-1.7.0.zip
cd seata/bin
./seata-server.sh -p 8091 -m file
<dependency>
<groupId>io.seatagroupId>
<artifactId>seata-spring-boot-starterartifactId>
<version>1.7.0version>
dependency>
# application.yml
seata:
enabled: true
application-id: ${spring.application.name}
tx-service-group: my_test_tx_group
service:
vgroup-mapping:
my_test_tx_group: default
grouplist:
default: 127.0.0.1:8091
config:
type: file
registry:
type: file
@Service
public class OrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private StorageService storageService;
@GlobalTransactional
public void createOrder(String userId, String commodityCode, Integer count) {
orderMapper.insert(userId, commodityCode, count);
storageService.deduct(commodityCode, count);
}
}
@Component
public class DeductStorageTccAction {
@TwoPhaseBusinessAction(name = "deductStorage")
public boolean prepare(BusinessActionContext ctx) {
// Try 阶段:预扣库存
return true;
}
@Commit
public boolean commit(BusinessActionContext ctx) {
// Confirm 阶段:正式扣库存
return true;
}
@Rollback
public boolean rollback(BusinessActionContext ctx) {
// Cancel 阶段:回滚操作
return true;
}
}
我们构建一个简单的电商系统,包含:
@FeignClient(name = "storage-service")
public interface StorageServiceClient {
@PostMapping("/storage/deduct")
Result deduct(@RequestParam String commodityCode, @RequestParam Integer count);
}
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private OrderService orderService;
@GetMapping("/create")
public Result createOrder(
@RequestParam String userId,
@RequestParam String commodityCode,
@RequestParam Integer count
) {
orderService.createOrder(userId, commodityCode, count);
return Result.success("下单成功");
}
}
已在第 5.5 节展示完整事务流程。
随着云原生的发展,Spring Cloud Alibaba 将更加注重与 Kubernetes、Dubbo、OpenTelemetry 等生态的融合,未来将提供更完善的可观测性和自动化运维能力。
问题 | 解答 |
---|---|
如何解决 Sentinel Dashboard 无法连接? | 确保客户端端口开放,并正确配置 -Dcsp.sentinel.transport.port 参数。 |
如何调试 Gateway 的路由规则? | 访问 /actuator/gateway/routes 查看当前路由信息。 |
Seata 的 AT 模式是否适用于所有数据库? | AT 模式目前主要支持 MySQL、Oracle、PostgreSQL 等主流关系型数据库。 |
GitHub 示例仓库
通过本篇博客,希望读者能够全面了解 Spring Cloud Alibaba 的核心组件,并能够在实际项目中熟练应用这些工具来构建高效、稳定的微服务系统。