今天,让我们深入探讨JavaScript的微服务架构设计。微服务架构是一种将应用拆分为小型、独立服务的架构模式,每个服务都运行在自己的进程中,通过轻量级的通信机制进行交互。
小知识:微服务架构的核心是将单体应用拆分为一组小型服务,每个服务都能独立部署、扩展和升级,从而提高系统的可维护性和可扩展性。
// 1. 基础服务类
class MicroService {
constructor(name, options = {}) {
this.name = name;
this.version = options.version || '1.0.0';
this.endpoints = new Map();
this.middleware = [];
}
// 注册路由
route(path, handler) {
this.endpoints.set(path, handler);
}
// 添加中间件
use(middleware) {
this.middleware.push(middleware);
}
// 处理请求
async handleRequest(path, request) {
const handler = this.endpoints.get(path);
if (!handler) {
throw new Error(`Endpoint ${path} not found`);
}
// 执行中间件链
let index = 0;
const next = async () => {
if (index < this.middleware.length) {
return this.middleware[index++](request, next);
}
return handler(request);
};
return next();
}
}
// 2. 服务注册中心
class ServiceRegistry {
constructor() {
this.services = new Map();
this.healthChecks = new Map();
}
// 注册服务
register(service, instance) {
if (!this.services.has(service.name)) {
this.services.set(service.name, new Set());
}
this.services.get(service.name).add(instance);
// 设置健康检查
this.setupHealthCheck(service.name, instance);
}
// 注销服务
unregister(serviceName, instance) {
const instances = this.services.get(serviceName);
if (instances) {
instances.delete(instance);
if (instances.size === 0) {
this.services.delete(serviceName);
}
}
}
// 获取服务实例
getInstances(serviceName) {
return Array.from(this.services.get(serviceName) || []);
}
// 设置健康检查
setupHealthCheck(serviceName, instance) {
const check = async () => {
try {
const response = await fetch(`${instance.url}/health`);
return response.ok;
} catch (error) {
return false;
}
};
const interval = setInterval(async () => {
const isHealthy = await check();
if (!isHealthy) {
this.unregister(serviceName, instance);
clearInterval(interval);
}
}, 30000); // 每30秒检查一次
this.healthChecks.set(instance, interval);
}
}
// 3. 服务发现
class ServiceDiscovery {
constructor(registry) {
this.registry = registry;
this.cache = new Map();
this.cacheTimeout = 60000; // 1分钟缓存
}
async discover(serviceName) {
const cached = this.cache.get(serviceName);
if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
return cached.instances;
}
const instances = this.registry.getInstances(serviceName);
this.cache.set(serviceName, {
instances,
timestamp: Date.now()
});
return instances;
}
}
// 1. 消息总线
class MessageBus {
constructor() {
this.subscribers = new Map();
this.messageQueue = [];
this.processing = false;
}
// 发布消息
publish(topic, message) {
this.messageQueue.push({ topic, message });
if (!this.processing) {
this.processQueue();
}
}
// 订阅主题
subscribe(topic, callback) {
if (!this.subscribers.has(topic)) {
this.subscribers.set(topic, new Set());
}
this.subscribers.get(topic).add(callback);
return () => {
const callbacks = this.subscribers.get(topic);
if (callbacks) {
callbacks.delete(callback);
}
};
}
// 处理消息队列
async processQueue() {
this.processing = true;
while (this.messageQueue.length > 0) {
const { topic, message } = this.messageQueue.shift();
const subscribers = this.subscribers.get(topic);
if (subscribers) {
const promises = Array.from(subscribers).map(callback =>
Promise.resolve().then(() => callback(message))
);
await Promise.all(promises);
}
}
this.processing = false;
}
}
// 2. RPC客户端
class RPCClient {
constructor(serviceDiscovery) {
this.serviceDiscovery = serviceDiscovery;
this.loadBalancer = new LoadBalancer();
}
async call(serviceName, method, params) {
const instances = await this.serviceDiscovery.discover(serviceName);
const instance = this.loadBalancer.select(instances);
const response = await fetch(`${instance.url}/${method}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
});
if (!response.ok) {
throw new Error(`RPC call failed: ${response.statusText}`);
}
return response.json();
}
}
// 3. API网关
class APIGateway {
constructor(serviceDiscovery) {
this.serviceDiscovery = serviceDiscovery;
this.routes = new Map();
this.middleware = [];
}
// 注册路由
route(path, serviceName, method) {
this.routes.set(path, { serviceName, method });
}
// 添加中间件
use(middleware) {
this.middleware.push(middleware);
}
// 处理请求
async handleRequest(path, request) {
const route = this.routes.get(path);
if (!route) {
throw new Error(`Route ${path} not found`);
}
// 执行中间件
for (const middleware of this.middleware) {
await middleware(request);
}
const instances = await this.serviceDiscovery.discover(route.serviceName);
const instance = this.loadBalancer.select(instances);
return this.forwardRequest(instance, route.method, request);
}
async forwardRequest(instance, method, request) {
const response = await fetch(`${instance.url}/${method}`, {
method: request.method,
headers: request.headers,
body: request.body
});
return response;
}
}
// 1. 负载均衡器
class LoadBalancer {
constructor() {
this.algorithms = new Map();
this.currentIndex = 0;
// 注册默认算法
this.registerAlgorithm('round-robin', this.roundRobin.bind(this));
this.registerAlgorithm('random', this.random.bind(this));
this.registerAlgorithm('least-connections', this.leastConnections.bind(this));
}
registerAlgorithm(name, algorithm) {
this.algorithms.set(name, algorithm);
}
select(instances, algorithm = 'round-robin') {
const selectedAlgorithm = this.algorithms.get(algorithm);
if (!selectedAlgorithm) {
throw new Error(`Algorithm ${algorithm} not found`);
}
return selectedAlgorithm(instances);
}
// 轮询算法
roundRobin(instances) {
const instance = instances[this.currentIndex];
this.currentIndex = (this.currentIndex + 1) % instances.length;
return instance;
}
// 随机算法
random(instances) {
const index = Math.floor(Math.random() * instances.length);
return instances[index];
}
// 最少连接算法
leastConnections(instances) {
return instances.reduce((min, instance) =>
instance.connections < min.connections ? instance : min
);
}
}
// 2. 熔断器
class CircuitBreaker {
constructor(options = {}) {
this.failureThreshold = options.failureThreshold || 5;
this.resetTimeout = options.resetTimeout || 60000;
this.failures = 0;
this.state = 'CLOSED';
this.lastFailure = null;
}
async execute(command) {
if (this.state === 'OPEN') {
if (Date.now() - this.lastFailure >= this.resetTimeout) {
this.state = 'HALF_OPEN';
} else {
throw new Error('Circuit breaker is OPEN');
}
}
try {
const result = await command();
this.onSuccess();
return result;
} catch (error) {
this.onFailure();
throw error;
}
}
onSuccess() {
this.failures = 0;
this.state = 'CLOSED';
}
onFailure() {
this.failures++;
this.lastFailure = Date.now();
if (this.failures >= this.failureThreshold) {
this.state = 'OPEN';
}
}
}
// 3. 降级处理
class Fallback {
constructor() {
this.handlers = new Map();
}
register(serviceName, handler) {
this.handlers.set(serviceName, handler);
}
async execute(serviceName, context) {
const handler = this.handlers.get(serviceName);
if (!handler) {
throw new Error(`No fallback handler for ${serviceName}`);
}
return handler(context);
}
}
// 1. 性能监控
class PerformanceMonitor {
constructor() {
this.metrics = new Map();
this.alerts = new Set();
}
// 记录指标
record(serviceName, metric, value) {
if (!this.metrics.has(serviceName)) {
this.metrics.set(serviceName, new Map());
}
const serviceMetrics = this.metrics.get(serviceName);
if (!serviceMetrics.has(metric)) {
serviceMetrics.set(metric, []);
}
serviceMetrics.get(metric).push({
value,
timestamp: Date.now()
});
this.checkThresholds(serviceName, metric, value);
}
// 设置告警阈值
setThreshold(serviceName, metric, threshold, callback) {
this.alerts.add({
serviceName,
metric,
threshold,
callback
});
}
// 检查阈值
checkThresholds(serviceName, metric, value) {
for (const alert of this.alerts) {
if (alert.serviceName === serviceName &&
alert.metric === metric &&
value > alert.threshold) {
alert.callback({
serviceName,
metric,
value,
threshold: alert.threshold
});
}
}
}
// 获取指标统计
getStats(serviceName, metric, timeRange) {
const metrics = this.metrics.get(serviceName)?.get(metric) || [];
const filteredMetrics = metrics.filter(
m => m.timestamp >= Date.now() - timeRange
);
return {
avg: this.average(filteredMetrics),
max: this.max(filteredMetrics),
min: this.min(filteredMetrics),
count: filteredMetrics.length
};
}
average(metrics) {
return metrics.reduce((sum, m) => sum + m.value, 0) / metrics.length;
}
max(metrics) {
return Math.max(...metrics.map(m => m.value));
}
min(metrics) {
return Math.min(...metrics.map(m => m.value));
}
}
// 2. 分布式追踪
class Tracer {
constructor() {
this.traces = new Map();
}
startSpan(name, parentId = null) {
const span = {
id: this.generateId(),
parentId,
name,
startTime: Date.now(),
endTime: null,
tags: new Map()
};
this.traces.set(span.id, span);
return span.id;
}
endSpan(spanId) {
const span = this.traces.get(spanId);
if (span) {
span.endTime = Date.now();
}
}
addTag(spanId, key, value) {
const span = this.traces.get(spanId);
if (span) {
span.tags.set(key, value);
}
}
getTrace(spanId) {
const span = this.traces.get(spanId);
if (!span) return null;
const children = Array.from(this.traces.values())
.filter(s => s.parentId === spanId);
return {
...span,
duration: span.endTime - span.startTime,
children: children.map(child => this.getTrace(child.id))
};
}
generateId() {
return Math.random().toString(36).substr(2, 9);
}
}
// 3. 日志聚合
class LogAggregator {
constructor() {
this.logs = [];
this.subscribers = new Set();
}
log(level, message, metadata = {}) {
const logEntry = {
timestamp: new Date(),
level,
message,
metadata
};
this.logs.push(logEntry);
this.notifySubscribers(logEntry);
}
subscribe(callback) {
this.subscribers.add(callback);
return () => this.subscribers.delete(callback);
}
notifySubscribers(logEntry) {
this.subscribers.forEach(callback => callback(logEntry));
}
query(filter) {
return this.logs.filter(log => {
for (const [key, value] of Object.entries(filter)) {
if (log[key] !== value) return false;
}
return true;
});
}
}
// 1. 服务边界定义
class ServiceBoundary {
constructor(service) {
this.service = service;
this.apis = new Set();
this.events = new Set();
}
// 定义公共API
exposeAPI(name, handler) {
this.apis.add({ name, handler });
this.service.route(name, handler);
}
// 定义事件
defineEvent(name, schema) {
this.events.add({ name, schema });
}
// 验证API调用
validateAPICall(name, params) {
const api = Array.from(this.apis)
.find(api => api.name === name);
if (!api) {
throw new Error(`API ${name} not found`);
}
// 验证参数
return true;
}
}
// 2. 错误处理
class ErrorHandler {
constructor() {
this.handlers = new Map();
}
// 注册错误处理器
register(errorType, handler) {
this.handlers.set(errorType, handler);
}
// 处理错误
handle(error) {
const handler = this.handlers.get(error.constructor);
if (handler) {
return handler(error);
}
// 默认错误处理
return {
status: 500,
message: 'Internal Server Error',
error: error.message
};
}
}
// 3. 版本控制
class VersionManager {
constructor() {
this.versions = new Map();
}
// 注册版本
register(version, implementation) {
this.versions.set(version, implementation);
}
// 获取特定版本的实现
getImplementation(version) {
return this.versions.get(version) ||
this.versions.get(this.getLatestVersion());
}
// 获取最新版本
getLatestVersion() {
return Array.from(this.versions.keys())
.sort((a, b) => b.localeCompare(a))[0];
}
}
微服务架构是构建大规模分布式系统的重要方法。通过本文,我们学习了:
学习建议:在实施微服务架构时,要注意服务的粒度和边界划分,避免服务之间的过度耦合。同时,要建立完善的监控和追踪机制,确保系统的可观测性。
如果你觉得这篇文章有帮助,欢迎点赞收藏,也期待在评论区看到你的想法和建议!
终身学习,共同成长。
咱们下一期见