Giter Site home page Giter Site logo

Re-queue with with x-delay about nestjs HOT 2 CLOSED

aviNrich avatar aviNrich commented on July 20, 2024 1
Re-queue with with x-delay

from nestjs.

Comments (2)

brknesn avatar brknesn commented on July 20, 2024 3

aviNrich I apply it this way.

I created a decorator named Requeueable:

export function Requeueable(maxRetries = 3, delayInMillis = 5000) {
    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        const originalMethod = descriptor.value;

        descriptor.value = async function (...args: any[]) {
            try {
                await originalMethod.apply(this, args);
            } catch (error) {
                const message = args[1]; // The message is the second argument to the method
                const retryCount = message.properties.headers?.retryCount || 0;

                await sleep(delayInMillis * retryCount);

                if (retryCount < maxRetries) {
                    console.error(`Error: ${error.message}, requeueing message. Retry Count: ${retryCount + 1}`);

                    const amqpConnection: AmqpConnection = this.amqpConnection; // Ensure AmqpConnection is injected into your service
                    await amqpConnection.publish(
                        message.fields.exchange,
                        message.fields.routingKey,
                        args[0],
                        {
                            headers: {
                                ...message.properties.headers,
                                retryCount: retryCount + 1,
                                'x-delay': delayInMillis * retryCount,
                            }
                        }
                    );

                    return new Nack();
                } else {
                    console.error(`Maximum retry count reached. Message will be discarded.`);
                    return new Nack();
                }
            }
        };

        return descriptor;
    };
}

And in my service, I use it like this:

const MAX_RETRIES = 50;
const RETRY_DELAY = 2000;

@Injectable()
export class RabbitmqHandler {
  constructor(
    private readonly amqpConnection: AmqpConnection,
  ) {}

  @RabbitSubscribe({
    exchange: 'initiation_exchange',
    routingKey: 'ScanReportCreatedEvent',
    queue: 'product-creation-queue',
    queueOptions: {
      durable: true,
      channel: 'product-creation-channel',
    },
    allowNonJsonMessages: true,
    createQueueIfNotExists: true,
  })
  @Requeueable(MAX_RETRIES, RETRY_DELAY)
  public async pubSubHandler(msg: {}, amqpMsg: ConsumeMessage) {
    throw new Error('test');
    }

from nestjs.

underfisk avatar underfisk commented on July 20, 2024

@brknesn Thank you for providing your Requeueable decorator

from nestjs.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.