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-redisor@alova/storage-fileas thel2Cacheof the Alova instance. @alova/storage-redisinternally uses @sesamecare-oss/redlock to implement a distributed lock. See the configuration forredlockin the redis storage adapter documentation.@alova/storage-fileinternally uses proper-lockfile to implement a file-based lock. See the configuration forproper-lockfilein the file storage adapter documentation.- Ensure that the lock is released after the request is completed to avoid deadlocks.
Is using alova in your project? please tell me!