Skip to content

Latest commit

 

History

History
111 lines (85 loc) · 2.24 KB

File metadata and controls

111 lines (85 loc) · 2.24 KB

6.3 API网关

📍 导航返回目录 | 上一节:配置中心 | 下一节:熔断降级


核心功能

  • 路由转发
  • 鉴权认证
  • 限流熔断
  • 日志监控
  • 协议转换

自研网关(Go)

package main

import (
    "net/http"
    "net/http/httputil"
    "net/url"
)

type Gateway struct {
    routes map[string]*httputil.ReverseProxy
    limiter *RateLimiter
    auth    *AuthMiddleware
}

func (gw *Gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // 1. 鉴权
    if !gw.auth.Validate(r) {
        http.Error(w, "Unauthorized", http.StatusUnauthorized)
        return
    }
    
    // 2. 限流
    if !gw.limiter.Allow(r.RemoteAddr) {
        http.Error(w, "Too Many Requests", http.StatusTooManyRequests)
        return
    }
    
    // 3. 路由转发
    path := r.URL.Path
    proxy, ok := gw.routes[path]
    if !ok {
        http.Error(w, "Not Found", http.StatusNotFound)
        return
    }
    
    proxy.ServeHTTP(w, r)
}

func NewGateway() *Gateway {
    gw := &Gateway{
        routes:  make(map[string]*httputil.ReverseProxy),
        limiter: NewRateLimiter(100),
        auth:    NewAuthMiddleware(),
    }
    
    // 注册路由
    gw.RegisterRoute("/api/users", "http://user-service:8080")
    gw.RegisterRoute("/api/orders", "http://order-service:8080")
    
    return gw
}

func (gw *Gateway) RegisterRoute(path, target string) {
    targetURL, _ := url.Parse(target)
    gw.routes[path] = httputil.NewSingleHostReverseProxy(targetURL)
}

Kong网关

# Kong配置
services:
  - name: user-service
    url: http://user-service:8080
    routes:
      - name: user-route
        paths:
          - /api/users
    plugins:
      - name: rate-limiting
        config:
          minute: 100
      - name: jwt

本章小结

关键要点

  • ✅ API网关是微服务入口
  • ✅ 统一鉴权、限流、监控
  • ✅ Kong成熟度高
  • ✅ 自研灵活性强

⏮️ 上一节:配置中心 | ⏭️ 下一节:熔断降级