百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程网 > 正文

使前端大放异彩的十二个设计模式

yuyutoo 2024-12-05 17:46 1 浏览 0 评论

微服务架构已成为现代、可扩展和弹性应用的核心。在本文中,我们将探讨使微服务大放异彩的强大设计模式,特别是在渐进式 Node.js 框架 NestJS 的上下文中。

? 网关模式(Gateway Pattern)

网关模式充当了所有微服务调用的单一入口点。它将请求路由到适当的服务,处理身份验证和日志记录,甚至可以聚合响应。

import { Module } from '@nestjs/common';
import { ClientsModule, Transport } from '@nestjs/microservices';
import { GatewayController } from './gateway.controller';

@Module({
  imports: [
    ClientsModule.register([
      { name: 'USER_SERVICE', transport: Transport.TCP },
      { name: 'ORDER_SERVICE', transport: Transport.TCP },
    ]),
  ],
  controllers: [GatewayController],
})
export class GatewayModule {}


import { Controller, Get } from '@nestjs/common'; 
import { ClientProxy, ClientProxyFactory, Transport } from '@nestjs/microservices';

@Controller('gateway') 
export class GatewayController { 
  private userServiceClient: ClientProxy; 
  private orderServiceClient: ClientProxy;

  constructor() { 
    this.userServiceClient = ClientProxyFactory.create({ transport: Transport.TCP, options: { port: 3001 }, }); 
    this.orderServiceClient = ClientProxyFactory.create({ transport: Transport.TCP, options: { port: 3002 }, }); 
  }

  @Get('user') getUser() { 
    return this.userServiceClient.send({ cmd: 'get-user' }, {}); 
  }

  @Get('order') getOrder() { 
    return this.orderServiceClient.send({ cmd: 'get-order' }, {}); 
  } 
}  

2. 服务注册中心模式(Service Registry Pattern)

服务注册中心模式允许微服务在不硬编码其位置的情况下相互发现。在服务可能更改 IP 或端口的动态环境中,这是至关重要的。

import { Injectable, OnModuleInit } from '@nestjs/common';
import { Consul } from 'consul';

@Injectable()
export class ServiceRegistry implements OnModuleInit {
  private consul: Consul;

  constructor() {
    this.consul = new Consul();
  }

  onModuleInit() {
    this.consul.agent.service.register({
      name: 'user-service',
      address: '127.0.0.1',
      port: 3001,
    });
  }
}

?断路器模式(Circuit Breaker Pattern)

断路器模式通过在服务故障或响应缓慢时断开电路并返回回退响应,防止微服务中的级联故障。

@Injectable() 
export class CircuitBreakerService { 
  constructor(private httpService: HttpService) {}

	getUserData() { 
    return this.httpService.get('http://user-service/user') 
      .pipe( catchError(err => { 
      	console.log('Service unavailable, returning fallback data'); 
        return of({ id: 'fallback', name: 'Fallback User' }); 
    	}) ); 
  } 
} 

4. SAGA 模式

SAGA 模式通过将复杂事务分解为更小的步骤来管理跨多个服务的复杂事务。SAGA 中的每个步骤要么成功完成,要么在出现问题时触发补偿事务来撤消先前的步骤。

import { Injectable } from '@nestjs/common';
import { EventPattern } from '@nestjs/microservices';

@Injectable()
export class SagaService {
  @EventPattern('order-created')
  async handleOrderCreated(data: Record<string, unknown>) {
    // Reserve inventory
    // If inventory reservation fails, trigger a compensating transaction
  }

  @EventPattern('payment-processed')
  async handlePaymentProcessed(data: Record<string, unknown>) {
    // Confirm order
    // If payment fails, trigger a compensating transaction to release inventory
  }
}

5. CQRS(命令查询职责分离)

CQRS 将读写操作分离,通过独立优化每种操作类型来提高性能。它在具有复杂查询要求的系统中特别有用。

import { QueryHandler, IQueryHandler } from '@nestjs/cqrs';

export class GetUserQuery {
  constructor(userId: string) {
    this.userId = userId;
  }
}

@QueryHandler(GetUserQuery)
export class GetUserHandler implements IQueryHandler<GetUserQuery> {
  async execute(query: GetUserQuery) {
    // Handle the query, e.g., return user data
    return { id: query.userId, name: 'John Doe' };
  }
} 

6. 舱壁模式(Bulkhead Pattern)

舱壁模式将服务中的组件隔离开来,以防止故障蔓延,确保一个服务出现故障不会导致其他服务崩溃。

import { Injectable } from '@nestjs/common';
import { Queue } from 'bull';

@Injectable()
export class BulkheadService {
  private readonly taskQueue: Queue;

  constructor() {
    this.taskQueue = new Queue('tasks');
  }

  async handleTask(taskData: any) {
    await this.taskQueue.add(taskData);
    // Process task without affecting other components
  }
}

7. 边车模式(Sidecar Pattern)

边车模式(Sidecar Pattern)在不改变核心服务逻辑的情况下为服务添加额外的功能(如监控、日志记录或代理)。

import { Injectable } from '@nestjs/common';
import { createProxyMiddleware } from 'http-proxy-middleware';

@Injectable()
export class SidecarService {
  configure(app) {
    app.use('/user', createProxyMiddleware({
      target: 'http://localhost:3001',
      changeOrigin: true
    }));
  }
} 

8. API 组合模式(API Composition Pattern)

API 组合将多个微服务组合成单个 API 响应,当构建聚合来自不同来源的数据的 API 时,这非常有用。

import { Controller, Get } from '@nestjs/common'; 
import { HttpService } from '@nestjs/common';

@Controller('orders') 
export class OrdersController { 
  constructor(private httpService: HttpService) {}

	@Get() 
  async getOrders() { 
    const user = await this.httpService.get('http://user-service/user').toPromise(); 
    const order = await this.httpService.get('http://order-service/order').toPromise(); 
    return {...user.data,...order.data }; 
  } 
}  

9. ?? 事件驱动架构(Event-Driven Architecture)

在事件驱动架构中,服务会异步响应事件,从而使系统更具响应性和松耦合性。

import { Controller } from '@nestjs/common';
import { EventPattern } from '@nestjs/microservices';

@Controller()
export class EventController {
  @EventPattern('user_created')
  handleUserCreated(data: Record<string, unknown>) {
    console.log('User created event received:', data);
    // React to the event
  }
}

10. 服务数据库(Database per Service)

每个微服务都拥有自己的数据,存储在自己的数据库中,确保数据的隔离和独立性。这种模式允许微服务独立演进。

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';

@Injectable()
export class UserService {
  constructor(@InjectRepository(User) private userRepository: Repository<User>) {}

  findAll() {
    return this.userRepository.find();
  }
}

重试模式(Retry Pattern)

重试模式通过重试失败的操作来处理瞬时故障,通常采用指数退避策略。

import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/common';
import { catchError, retryWhen, delay, take } from 'rxjs/operators';
import { of } from 'rxjs';

@Injectable()
export class RetryService {
  constructor(httpService: HttpService) {}

  fetchData() {
    return this.httpService.get('http://unreliable-service/data')
     .pipe(
        retryWhen(errors => errors.pipe(delay(1000), take(3))),
        catchError(err => {
          console.log('Failed after retries');
          return of({ fallback: true });
        })
      );
  }
} 

配置外部化(Configuration Externalization)

配置外部化将配置管理集中化,使更改配置而无需重新部署服务变得更加容易。

import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: '.env',
    }),
  ],
})
export class AppModule {}

结论

微服务架构与上述设计模式相结合,可以使应用程序变得灵活、有弹性且可扩展。NestJS 凭借其模块化方法和强大的抽象,是实现这些模式的绝佳框架,可确保您的应用程序能够处理现代分布式系统的复杂性。

相关推荐

如何在HTML中使用JavaScript:从基础到高级的全面指南!

“这里是云端源想IT,帮你...

推荐9个Github上热门的CSS开源框架

大家好,我是Echa。...

前端基础知识之“CSS是什么?”_前端css js

...

硬核!知网首篇被引过万的论文讲了啥?作者什么来头?

整理|袁小华近日,知网首篇被引量破万的中文论文及其作者备受关注。知网中心网站数据显示,截至2021年7月23日,由华南师范大学教授温忠麟等人发表在《心理学报》2004年05期上的学术论文“中介效应检验...

为什么我推荐使用JSX开发Vue3_为什么用vue不用jquery

在很长的一段时间中,Vue官方都以简单上手作为其推广的重点。这确实给Vue带来了非常大的用户量,尤其是最追求需求开发效率,往往不那么在意工程代码质量的国内中小企业中,Vue占据的份额极速增长...

【干货】一文详解html和css,前端开发需要哪些技术?
【干货】一文详解html和css,前端开发需要哪些技术?

网站开发简介...

2025-02-20 18:34 yuyutoo

分享几个css实用技巧_cssli

本篇将介绍几个css小技巧,目录如下:自定义引用标签的符号重置所有标签样式...

如何在浏览器中运行 .NET_怎么用浏览器运行代码

概述:...

前端-干货分享:更牛逼的CSS管理方法-层(CSS Layers)

使用CSS最困难的部分之一是处理CSS的权重值,它可以决定到底哪条规则会最终被应用,尤其是如果你想在Bootstrap这样的框架中覆盖其已有样式,更加显得麻烦。不过随着CSS层的引入,这一...

HTML 基础标签库_html标签基本结构
HTML 基础标签库_html标签基本结构

HTML标题HTML标题(Heading)是通过-...

2025-02-20 18:34 yuyutoo

前端css面试20道常见考题_高级前端css面试题

1.请解释一下CSS3的flexbox(弹性盒布局模型),以及适用场景?display:flex;在父元素设置,子元素受弹性盒影响,默认排成一行,如果超出一行,按比例压缩flex:1;子元素设置...

vue引入外部js文件并使用_vue3 引入外部js

要在Vue中引入外部的JavaScript文件,可以使用以下几种方法:1.使用``标签引入外部的JavaScript文件。在Vue的HTML模板中,可以直接使用``标签来引入外部的JavaScrip...

网页设计得懂css的规范_html+css网页设计

在初级的前端工作人员,刚入职的时候,可能在学习前端技术,写代码不是否那么的规范,而在工作中,命名的规范的尤为重要,它直接与你的代码质量挂钩。网上也受很多,但比较杂乱,在加上每年的命名都会发生一变化。...

Google在Chrome中引入HTML 5.1标记

虽然负责制定Web标准的WorldWideWebConsortium(W3C)尚未宣布HTML5正式推荐规格,而Google已经迁移到了HTML5.1。即将发布的Chrome38将引入H...

HTML DOM 引用( ) 对象_html中如何引用js

引用对象引用对象定义了一个同内联元素的HTML引用。标签定义短的引用。元素经常在引用的内容周围添加引号。HTML文档中的每一个标签,都会创建一个引用对象。...

取消回复欢迎 发表评论: