尚硅谷2025最新SpringCloud速通-实战避坑指南

张开发
2026/4/9 2:50:06 15 分钟阅读

分享文章

尚硅谷2025最新SpringCloud速通-实战避坑指南
1. SpringCloud微服务实战避坑指南最近在尚硅谷2025最新SpringCloud课程中我完整走了一遍微服务项目搭建流程。作为过来人整理了几个新手最容易踩的坑点特别是Nacos、OpenFeign这些核心组件的配置细节。下面这些经验都是我用真金白银的线上事故换来的建议收藏备用。先说说我遇到最典型的问题Nacos服务注册后其他服务死活找不到实例。后来发现是spring-cloud-alibaba版本和spring-boot版本不兼容导致的。这里特别提醒SpringBoot 3.x必须搭配2023.x以上的SpringCloud Alibaba否则会出现各种灵异问题。2. Nacos服务注册与发现2.1 版本兼容性配置在父pom中必须严格锁定版本这是我推荐的配置组合parent groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-parent/artifactId version3.3.4/version /parent properties spring-cloud.version2023.0.3/spring-cloud.version spring-cloud-alibaba.version2023.0.3.2/spring-cloud-alibaba.version /properties踩坑记录曾因为用了SpringBoot 3.1.0 SpringCloud 2022.0.0导致Nacos客户端自动注册失败控制台不报错但服务就是找不到。2.2 服务注册关键步骤每个微服务模块需要添加依赖dependency groupIdcom.alibaba.cloud/groupId artifactIdspring-cloud-starter-alibaba-nacos-discovery/artifactId /dependency配置文件必须包含三要素spring.application.nameservice-order # 服务名必须全小写 spring.cloud.nacos.server-addr127.0.0.1:8848 server.port8000 # 不同实例端口需不同启动类别忘了加注解EnableDiscoveryClient // 这个不能少 SpringBootApplication public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class, args); } }2.3 服务发现实战技巧通过DiscoveryClient获取服务实例时我推荐使用负载均衡的写法Service public class OrderServiceImpl { Autowired private LoadBalancerClient loadBalancerClient; public void callProductService() { ServiceInstance instance loadBalancerClient.choose(service-product); String url http://instance.getHost():instance.getPort()/product/1; // 发起请求... } }更简洁的写法是用LoadBalanced注解Bean LoadBalanced // 开启负载均衡 public RestTemplate restTemplate() { return new RestTemplate(); } // 使用时直接写服务名 String url http://service-product/product/1;3. OpenFeign远程调用优化3.1 基础配置在服务调用方添加依赖dependency groupIdorg.springframework.cloud/groupId artifactIdspring-cloud-starter-openfeign/artifactId /dependency声明式接口写法示例FeignClient(name service-product, path /product, configuration FeignConfig.class) public interface ProductFeignClient { GetMapping(/{id}) Product getById(PathVariable Long id); }3.2 超时控制在application.yml中配置feign: client: config: default: connectTimeout: 5000 # 连接超时5秒 readTimeout: 30000 # 读取超时30秒我遇到过的一个坑没有配置超时导致线程池被占满整个服务雪崩。建议生产环境超时时间不要超过30秒。3.3 熔断降级结合Sentinel实现熔断FeignClient(name service-product, fallback ProductFeignFallback.class) public interface ProductFeignClient { //... } Component public class ProductFeignFallback implements ProductFeignClient { Override public Product getById(Long id) { // 返回兜底数据 return new Product(id, 默认商品, BigDecimal.ZERO); } }需要在配置中开启Sentinel支持feign: sentinel: enabled: true4. Sentinel流量控制4.1 控制台搭建下载sentinel-dashboard-1.8.8.jar后启动java -Dserver.port8080 -jar sentinel-dashboard.jar接入微服务的配置spring: cloud: sentinel: transport: dashboard: localhost:8080 eager: true # 立即初始化4.2 流控规则配置通过SentinelResource定义资源GetMapping(/seckill) SentinelResource(value seckill, blockHandler seckillBlock, fallback seckillFallback) public Order seckill() { // 业务逻辑 } // 流控处理 public Order seckillBlock(BlockException ex) { return new Order(系统繁忙请重试); } // 异常处理 public Order seckillFallback(Throwable ex) { return new Order(服务暂时不可用); }4.3 热点参数限流特殊商品需要单独限流SentinelResource(value hotProduct, blockHandler hotProductBlock) GetMapping(/product/{id}) public Product getProduct(PathVariable Long id) { //... }在Sentinel控制台配置资源名hotProduct参数索引0 (对应id参数)单机阈值普通商品100特殊商品(id666)设置为15. Seata分布式事务5.1 环境搭建下载Seata Server并启动每个微服务添加依赖dependency groupIdcom.alibaba.cloud/groupId artifactIdspring-cloud-starter-alibaba-seata/artifactId /dependency配置文件file.confservice.vgroupMapping.default_tx_groupdefault5.2 事务使用在事务发起方GlobalTransactional // 开启全局事务 public void createOrder() { // 1. 扣减库存 storageFeignClient.deduct(); // 2. 创建订单 orderMapper.create(); // 3. 扣减余额 accountFeignClient.debit(); }在参与方服务Transactional // 本地事务 public void deduct() { // 扣减库存SQL }踩过的坑Seata的AT模式需要每个参与方都有undo_log表建表SQL千万别漏CREATE TABLE undo_log ( id bigint(20) NOT NULL AUTO_INCREMENT, branch_id bigint(20) NOT NULL, xid varchar(100) NOT NULL, context varchar(128) NOT NULL, rollback_info longblob NOT NULL, PRIMARY KEY (id), UNIQUE KEY ux_undo_log (xid,branch_id) ) ENGINEInnoDB DEFAULT CHARSETutf8;6. Gateway网关配置6.1 基础路由典型配置示例spring: cloud: gateway: routes: - id: order-service uri: lb://service-order predicates: - Path/api/order/** filters: - RewritePath/api/order/(?segment.*), /$\{segment}6.2 全局过滤器记录请求耗时Component Slf4j public class RequestTimeFilter implements GlobalFilter, Ordered { Override public MonoVoid filter(ServerWebExchange exchange, GatewayFilterChain chain) { long start System.currentTimeMillis(); return chain.filter(exchange).then(Mono.fromRunnable(() - { long duration System.currentTimeMillis() - start; log.info({} 耗时 {}ms, exchange.getRequest().getURI(), duration); })); } Override public int getOrder() { return -1; } }6.3 跨域处理推荐配置spring: cloud: gateway: globalcors: cors-configurations: [/**]: allowedOrigins: * allowedMethods: - GET - POST - PUT - DELETE7. 配置中心最佳实践7.1 多环境配置通过namespace隔离环境spring: cloud: nacos: config: namespace: ${spring.profiles.active} group: DEFAULT_GROUP file-extension: yaml profiles: active: dev # 激活dev环境7.2 动态刷新两种刷新方式传统方式需要重启RefreshScope RestController public class ConfigController { Value(${config.item}) private String configItem; }推荐方式无感知刷新Component ConfigurationProperties(prefix config) Data public class ConfigProperties { private String item; }8. 微服务调试技巧8.1 请求链路追踪在application.yml中添加spring: sleuth: sampler: probability: 1.0 # 100%采样 zipkin: base-url: http://localhost:94118.2 接口文档聚合使用SpringDoc OpenAPI整合SwaggerBean public GroupedOpenApi publicApi() { return GroupedOpenApi.builder() .group(public-apis) .pathsToMatch(/api/**) .build(); }访问地址http://localhost:8080/swagger-ui.html9. 性能优化建议Feign客户端启用GZIP压缩feign: compression: request: enabled: true response: enabled: trueGateway添加缓存过滤器Bean public FilterRegistrationBeanCachingFilter cachingFilter() { FilterRegistrationBeanCachingFilter bean new FilterRegistrationBean(); bean.setFilter(new CachingFilter()); bean.addUrlPatterns(/static/*); return bean; }JVM参数建议-Xms512m -Xmx512m -XX:UseG1GC -XX:MaxGCPauseMillis20010. 生产环境注意事项Nacos集群至少3节点推荐使用MySQL持久化Sentinel规则需要持久化到NacosSeata服务端需要配置高可用所有微服务需要添加健康检查端点management: endpoints: web: exposure: include: health,info日志收集建议使用ELK或LokiGranfa方案最后提醒微服务不是银弹项目初期如果团队规模小于10人建议先用单体架构。我见过太多为了微服务而微服务最后被复杂度拖垮的项目。

更多文章