Skip to main content
Version: v3

Atomize Requests

type

server hook

alova@3.4.0+

The atomize strategy can be used to ensure atomicity of requests in multi-process environments.

Features

  • Ensures atomicity of requests in multi-process environments;
  • Customizable lock channels, timeout, and retry intervals;

Usage

Basic Usage

const { atomize } = require('alova/server');
const { alovaInstance } = require('./api');

const res = await atomize(alovaInstance.Get('/api/user'));

By default, atomize uses the channel name 'default', a timeout of 5000ms, and a retry interval of 100ms.

Customizing Lock Channel

You can specify a custom channel name or an array of channel names for locking, and different channels will not affect each other.

const hookedMethod = atomize(request, {
// Set a custom channel name
channel: 'user_lock'
// Or multiple channels
// channel: ['user_lock', 'order_lock']
});

Customizing Timeout and Interval

You can adjust the timeout for acquiring the lock and the interval between retries.

const hookedMethod = atomize(request, {
// Set timeout to 10 seconds
timeout: 10000,
// Set retry interval to 200ms
interval: 200
});

Error Handling

If the lock cannot be acquired within the specified timeout, an error will be thrown.

try {
const response = await atomize(request);
} catch (error) {
console.error('Failed to acquire lock:', error.message);
}

Notes

  • This strategy requires @alova/storage-redis or @alova/storage-file as the l2Cache of the Alova instance.
  • @alova/storage-redis internally uses @sesamecare-oss/redlock to implement a distributed lock. See the configuration for redlock in the redis storage adapter documentation.
  • @alova/storage-file internally uses proper-lockfile to implement a file-based lock. See the configuration for proper-lockfile in the file storage adapter documentation.
  • Ensure that the lock is released after the request is completed to avoid deadlocks.