Skip to content

Commit

Permalink
feat: only read from master (#623)
Browse files Browse the repository at this point in the history
set options.masterOnly = true to enable the feature

pick from #622
  • Loading branch information
fengmk2 authored and PeterRao committed Oct 21, 2019
1 parent 655ee3d commit 6357340
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/cluster.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ module.exports = function (OssClient) {
}

this.schedule = options.schedule || RR;
// only read from master, default is false
this.masterOnly = !!options.masterOnly;
this.index = 0;

const heartbeatInterval = options.heartbeatInterval || 10000;
Expand Down Expand Up @@ -180,6 +182,10 @@ module.exports = function (OssClient) {

proto.chooseAvailable = function chooseAvailable() {
if (this.schedule === MS) {
// only read from master
if (this.masterOnly) {
return this.clients[0];
}
for (let i = 0; i < this.clients.length; i++) {
if (this.availables[i]) {
return this.clients[i];
Expand Down
17 changes: 17 additions & 0 deletions test/node/cluster.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,23 @@ describe('test/cluster.test.js', () => {
this.store.removeListener('error', onerror);
});

it('should MS always get from clients[0] when masterOnly === true', async function () {
mm(this.store, 'schedule', 'masterSlave');
mm(this.store, 'masterOnly', true);
mm(this.store.clients[1], 'get', 'mock error');
function onerror() {
throw new Error('should not emit error event');
}
this.store.on('error', onerror);

let res = await this.store.get(this.name);
res.res.status.should.equal(200);
res = await this.store.get(this.name);
res.res.status.should.equal(200);

this.store.removeListener('error', onerror);
});

it('should get from clients[0] when clients[0] response 4xx ok', async function () {
mm(this.store, 'schedule', 'masterSlave');
mm.error(this.store.clients[0], 'get', 'mock error', { status: 403 });
Expand Down

0 comments on commit 6357340

Please sign in to comment.