Skip to content

Commit

Permalink
Add read preference to support reading from secondaries in MongoDB re…
Browse files Browse the repository at this point in the history
…plica sets
  • Loading branch information
lmsilva-wls committed Jul 13, 2021
1 parent 4d99051 commit 7cd663e
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion mongoclient/mongoclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (

"github.com/topfreegames/mqtt-history/models"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/readpref"

"github.com/spf13/viper"
"github.com/topfreegames/mqtt-history/logger"
Expand Down Expand Up @@ -56,7 +57,14 @@ func GetCollection(collection string, s func(collection *mongo.Collection) error
if err != nil {
return err
}
c := mongoDB.Database(database).Collection(collection)
// staleness: check how old the data is before reading from Secondary replicas
secondaryPreferredOpts := readpref.WithMaxStaleness(90 * time.Second)
// secondaryPreferred: prefer reading from Secondary replicas, falling back to the primary if needed
secondaryPreferred := readpref.SecondaryPreferred(secondaryPreferredOpts)
dbOpts := options.Database().
SetReadPreference(secondaryPreferred)

c := mongoDB.Database(database, dbOpts).Collection(collection)
return s(c)
}

Expand Down

0 comments on commit 7cd663e

Please sign in to comment.