Spring Cloud 微服务最佳实践

从 Consul 集群搭建、API/Domain 分包规范,到 OpenFeign、Ribbon、Hystrix 参数调优与 Actuator 安全隔离的落地清单。

基于前期 Spring Cloud 调研报告 的选型结论,我们确定了以下基础技术栈:

  • 注册中心:Consul 集群
  • RPC 组件:Ribbon + Hystrix + OpenFeign + Apache HttpClient
  • 监控管理:Sleuth + Apache SkyWalking + Spring Boot Admin

本文整理这套方案在工程落地时的具体配置与避坑细节。


Consul 集群搭建

Consul 集群通常由若干 Server 节点(含引导节点 Bootstrap)以及可选的 Client 节点组成。存在防火墙时需按需放通以下默认端口:

  • 8300:Server RPC / 复制端口
  • 8301:LAN Gossip 端口
  • 8302:WAN Gossip 端口
  • 8500:HTTP API 与 UI 端口
  • 8600:DNS 服务端口

启动 Bootstrap 节点

1
2
3
4
5
6
consul agent -bootstrap-expect 1 -server -ui \
  -log-file /export/log/consul/consul.log \
  -data-dir /export/data/consul \
  -config-dir /export/data/consul \
  -node=node1 -bind=10.28.6.41 -client=10.28.6.41 \
  -enable-script-checks=true -datacenter=default
  • -bootstrap-expect:最小 Server 集群规模(建议为 N/2 + 1)
  • -client:UI 与 HTTP API 绑定地址(默认 127.0.0.1)

启动普通 Server 节点

1
2
3
4
5
6
7
consul agent -server \
  -log-file /export/log/consul/consul.log \
  -data-dir /export/data/consul \
  -config-dir /export/data/consul \
  -node=node2 -bind=10.28.6.79 \
  -enable-script-checks=true -datacenter=default \
  -retry-join 10.28.6.41

工程结构与分包规范

在服务治理思想上,Spring Cloud 与 Dubbo 有很多相通之处(可参考 Dubbo 最佳实践)。为了统一接口契约、降低接入成本,建议通过独立二方库共享 api 与 domain:

1
2
3
4
5
6
7
8
├── api
│   ├── service-a-api
│   └── service-b-api
├── domain
│   ├── domain-a
│   └── domain-b
├── exception
└── util

在 REST 接口定义中约定统一路径与方法:

1
2
3
4
5
6
@RequestMapping(value = "/serviceA")
public interface ServiceA {

    @RequestMapping(value = "/invokeB", method = RequestMethod.GET)
    TrackInfo invokeB();
}

服务发布与注册配置

Spring MVC 实现注意事项

由于 Spring MVC 在解析接口映射时默认不会继承接口方法参数上的注解(如 @RequestBody、@PathVariable),服务实现类必须补全参数注解:

1
2
3
4
5
6
7
8
9
@RestController
public class ServiceBController implements ServiceB {

    @Override
    public TrackInfo stop(@RequestBody TrackInfo trackInfo) {
        // 业务逻辑
        return trackInfo;
    }
}

Consul 服务发现配置

在容器环境下主机名可能重复或不可路由,建议开启 prefer-ip-address 并显式指定唯一 instance-id:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
spring:
  application:
    name: ${serviceId}
  cloud:
    consul:
      host: 10.28.6.79
      port: 8500
      discovery:
        prefer-ip-address: true
        instance-id: ${serviceId}:${spring.cloud.client.ip-address}:${server.port}

服务消费与核心参数调优

基于共享接口包,消费端只需继承接口并声明 @FeignClient:

1
2
3
@FeignClient(value = "${serviceId.serviceB}")
public interface ServiceBClient extends ServiceB {
}

OpenFeign / Ribbon / Hystrix 推荐配置

OpenFeign:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
feign:
  httpclient:
    max-connections-per-route: 10
    max-connections: 500
  hystrix:
    enabled: true
  compression:
    request:
      enabled: true
    response:
      enabled: true

Ribbon:

1
2
3
4
5
6
ribbon:
  eager-load:
    enabled: true
  http:
    client:
      enabled: true

Hystrix:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 10000
  threadpool:
    default:
      coreSize: 10
      allowMaximumSizeToDivergeFromCoreSize: true
      maximumSize: 50
      maxQueueSize: 10
      keepAliveTimeMinutes: 5

避坑:屏蔽 FeignClient 被误注册为 Spring MVC Handler

当消费端本身也是 Web 服务时,由于 @FeignClient 继承了带 @RequestMapping 的公共接口,Spring MVC 会把该 Feign 接口误识别为本地 Controller 映射。需配置 WebMvcRegistrations 过滤掉带 @FeignClient 注解的接口:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
@Bean
public WebMvcRegistrations feignWebRegistrations() {
    return new WebMvcRegistrations() {
        @Override
        public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
            return new RequestMappingHandlerMapping() {
                @Override
                protected boolean isHandler(Class<?> beanType) {
                    return super.isHandler(beanType)
                            && !AnnotatedElementUtils.hasAnnotation(beanType, FeignClient.class);
                }
            };
        }
    };
}

Actuator 端口隔离

如果未启用 Spring Security 鉴权,务必将 Actuator 管理端口与业务端口分离,仅允许内网访问或仅暴露健康检查端点:

1
2
3
management:
  server:
    port: 8101
使用 Hugo 构建
主题 Stack 由 Jimmy 设计