微服务架构:API网关与服务发现
微服务架构:API网关与服务发现
大家好,我是欧阳瑞(Rich Own)。今天想和大家聊聊微服务架构这个重要话题。作为一个全栈开发者,API网关和服务发现是微服务架构的核心组件。今天就来分享一下API网关和服务发现的实战经验。
微服务架构概述
什么是微服务?
微服务是一种架构风格 将应用拆分成多个独立的服务 每个服务独立部署和扩展核心组件
| 组件 | 说明 |
|---|---|
| API网关 | 统一入口,路由转发 |
| 服务发现 | 服务注册和发现 |
| 负载均衡 | 流量分发 |
| 熔断降级 | 故障处理 |
API网关
Kong配置
# docker-compose.yml version: '3.7' services: kong: image: kong:latest ports: - "8000:8000" - "8443:8443" - "8001:8001" environment: KONG_DATABASE: postgres KONG_PG_HOST: kong-db KONG_PG_USER: kong KONG_PG_PASSWORD: kong添加服务
# 添加服务 curl -X POST http://localhost:8001/services \ --data name=user-service \ --data url=http://user-service:3000 # 添加路由 curl -X POST http://localhost:8001/services/user-service/routes \ --data paths[]=/api/users配置插件
# 添加认证插件 curl -X POST http://localhost:8001/services/user-service/plugins \ --data name=key-auth # 添加限流插件 curl -X POST http://localhost:8001/services/user-service/plugins \ --data name=rate-limiting \ --data config.minute=100 \ --data config.hour=1000服务发现
Consul配置
# docker-compose.yml version: '3.7' services: consul: image: consul:latest ports: - "8500:8500" - "8600:8600/udp" command: agent -server -ui -node=server-1 -bootstrap-expect=1服务注册
const consul = require('consul')(); async function registerService() { await consul.agent.service.register({ name: 'user-service', address: 'localhost', port: 3000, check: { http: 'http://localhost:3000/health', interval: '10s', timeout: '5s' } }); }服务发现
async function discoverService(serviceName) { const result = await consul.catalog.service.nodes(serviceName); const nodes = result.map(node => `${node.Address}:${node.ServicePort}`); return nodes; }实战案例:完整微服务架构
class APIGateway { constructor() { this.routes = {}; this.serviceDiscovery = new ServiceDiscovery(); } async handleRequest(req) { const route = this.findRoute(req.path); if (!route) { return { status: 404, body: 'Not found' }; } const serviceNodes = await this.serviceDiscovery.discover(route.service); if (serviceNodes.length === 0) { return { status: 503, body: 'Service unavailable' }; } // 负载均衡 const target = this.selectNode(serviceNodes); // 转发请求 const response = await this.forwardRequest(req, target); return response; } selectNode(nodes) { // 简单轮询 return nodes[Math.floor(Math.random() * nodes.length)]; } }最佳实践
1. 健康检查
// 健康检查端点 app.get('/health', (req, res) => { const health = { status: 'healthy', timestamp: Date.now(), uptime: process.uptime() }; res.json(health); });2. 日志追踪
// 分布式追踪 app.use((req, res, next) => { const traceId = req.headers['x-trace-id'] || uuid.v4(); req.traceId = traceId; res.on('finish', () => { console.log(`${traceId} ${req.method} ${req.path} ${res.statusCode}`); }); next(); });总结
API网关和服务发现是微服务架构的核心组件。通过合理配置和使用,可以构建高效、可靠的微服务系统。
我的鬃狮蜥Hash对微服务也有自己的理解——它总是把不同的任务分配给不同的区域,这也许就是自然界的"微服务架构"吧!
如果你对微服务架构有任何问题,欢迎留言交流!我是欧阳瑞,极客之路,永无止境!
技术栈:微服务架构 · API网关 · 服务发现
