How to use preferredSlaves for slave selection
mainIf you set role: 'slave', you can use preferredSlaves to control which slave is selected from the pool. You can provide either an array of priorities or a selection function.
Option 1: Priority Array
An array of slave objects ordered by priority (lowest prio value first). The default prio is 1.
Option 2: Selection Function
A function that receives an array of availableSlaves and returns a single slave object or false to fall back to a random slave.
Available Slave Object Format:
{ ip: string, port: string, flags: string }
// available slaves format
const availableSlaves = [{ ip: "127.0.0.1", port: "31231", flags: "slave" }];
// preferredSlaves array format
let preferredSlaves = [
{ ip: "127.0.0.1", port: "31231", prio: 1 },
{ ip: "127.0.0.1", port: "31232", prio: 2 },
];
// preferredSlaves function format
preferredSlaves = function (availableSlaves) {
for (let i = 0; i < availableSlaves.length; i++) {
const slave = availableSlaves[i];
if (slave.ip === "127.0.0.1") {
if (slave.port === "31234") {
return slave;
}
}
}
// if no preferred slaves are available a random one is used
return false;
};
const valkey = new Valkey({
sentinels: [
{ host: "127.0.0.1", port: 26379 },
{ host: "127.0.0.1", port: 26380 },
],
name: "mymaster",
role: "slave",
preferredSlaves: preferredSlaves,
});