第 8 章:边缘服务
本章系统梳理了边缘服务在微服务架构中的定位与作用,涵盖 API 适配、客户端负载均衡、OAuth 安全、Zuul 网关与 CORS 处理等关键技术,帮助开发者构建高效、安全、可扩展的云原生边缘层。
边缘服务的定位与挑战
微服务最终要为多样化的客户端(Web、移动、IoT 等)提供服务。不同客户端对数据格式、内容量、交互模型等有不同需求。为避免每个微服务都适配所有客户端,通常在系统边界设置边缘服务(API Gateway/BFF),统一处理认证、限流、协议适配、路由等横切关注点。
基础服务搭建:Eureka 与 Greetings 服务
首先,搭建 Netflix Eureka 服务注册中心(service-registry),并注册 greetings-service。Eureka 通过 @EnableEurekaServer
启动,配置项需关闭自注册和自我保护(开发环境):
@SpringBootApplication
@EnableEurekaServer
public class EurekaServiceApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServiceApplication.class, args);
}
}
spring.application.name=eureka-service
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.server.enable-self-preservation=false
greetings-service 作为 REST 服务注册到 Eureka,暴露 /greet/{name}
端点,返回问候语。
构建边缘服务:API 适配与客户端负载均衡
边缘服务(如 greetings-client)作为 API 适配器,统一对外暴露接口,并通过 Spring Cloud DiscoveryClient、Ribbon、RestTemplate 或 Feign 实现下游服务调用与负载均衡。
RestTemplate 方式
@RestController
@RequestMapping("/api")
class RestTemplateGreetingsClientApiGateway {
@Autowired
public RestTemplateGreetingsClientApiGateway(@LoadBalanced RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@GetMapping("/resttemplate/{name}")
public Map<String, String> restTemplate(@PathVariable String name) {
// 通过 Ribbon + RestTemplate 负载均衡调用 greetings-service
// 返回 Map<String, String>
}
}
Feign 方式
@FeignClient(serviceId = "greetings-service")
interface GreetingsClient {
@RequestMapping(method = RequestMethod.GET, value = "/greet/{name}")
Map<String, String> greet(@PathVariable("name") String name);
}
@RestController
@RequestMapping("/api")
class FeignGreetingsClientApiGateway {
@Autowired
public FeignGreetingsClientApiGateway(GreetingsClient greetingsClient) {
this.greetingsClient = greetingsClient;
}
@GetMapping("/feign/{name}")
public Map<String, String> feign(@PathVariable String name) {
return greetingsClient.greet(name);
}
}
网关与过滤:Netflix Zuul
Zuul 作为边缘网关,支持动态路由、过滤、限流等功能。通过 @EnableZuulProxy
快速集成,自动代理注册中心服务。可通过配置自定义路由规则:
zuul.routes.hi.path = /lets/**
zuul.routes.hi.serviceId = greetings-service
支持动态刷新路由,结合 Spring Cloud Config 实现无缝配置变更。
CORS 与跨源访问控制
为支持浏览器等跨域客户端,边缘服务需处理 CORS。推荐在边缘层统一添加 CORS 过滤器,动态判断请求来源是否为注册中心已知服务,自动设置 Access-Control-Allow-Origin
等头信息,提升安全性与灵活性。
OAuth 安全与单点登录
边缘服务是安全防线的首选位置。通过 Spring Security OAuth 实现授权服务器(auth-service)、资源服务器(greetings-service)、边缘服务(edge-service)三层分离,支持多种 OAuth 授权模式(授权码、简化、密码、客户端模式)。
- 授权服务器负责颁发令牌,集成 UserDetailsService、ClientDetailsService。
- 资源服务器通过
@EnableResourceServer
注解保护 REST API,仅允许携带有效令牌的请求访问。 - 边缘服务通过
@EnableOAuth2Sso
实现单点登录,前端可通过 Angular/React 等框架集成认证流程。
Zuul 自定义过滤器与限流
可通过自定义 ZuulFilter 实现限流、认证、日志等功能。例如,结合 Guava RateLimiter 实现全局或服务级别的请求速率限制,提升系统稳定性。
典型前端集成流程
HTML5/JS 客户端通过边缘服务获取 API URI,发起跨域请求,边缘服务统一处理认证、路由、CORS。推荐使用 WebJars 管理前端依赖,提升构建与部署效率。
总结
本章系统梳理了边缘服务的核心职责与实现方式,包括 API 适配、客户端负载均衡、OAuth 安全、Zuul 网关、CORS 处理等。通过合理设计边缘层,微服务系统可实现高效、安全、灵活的对外服务能力,支撑多样化客户端与复杂业务场景。