Skip to content

Commit

Permalink
add Mongodb pool configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
khannedy committed Feb 25, 2021
1 parent 94c3d38 commit 4557dce
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
5 changes: 4 additions & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
MONGO_URI=mongodb://mongo:mongo@localhost:27017
MONGO_DATABASE=golang
MONGO_DATABASE=golang
MONGO_POOL_MIN=10
MONGO_POOL_MAX=100
MONGO_MAX_IDLE_TIME_SECOND=60
5 changes: 4 additions & 1 deletion .env.test
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
MONGO_URI=mongodb://mongo:mongo@localhost:27017
MONGO_DATABASE=golang_test
MONGO_DATABASE=golang_test
MONGO_POOL_MIN=10
MONGO_POOL_MAX=100
MONGO_MAX_IDLE_TIME_SECOND=60
18 changes: 17 additions & 1 deletion config/mongo.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,30 @@ import (
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"golang-clean-architecture/exception"
"strconv"
"time"
)

func NewMongoDatabase(configuration Config) *mongo.Database {
ctx, cancel := NewMongoContext()
defer cancel()

client, err := mongo.NewClient(options.Client().ApplyURI(configuration.Get("MONGO_URI")))
mongoPoolMin, err := strconv.Atoi(configuration.Get("MONGO_POOL_MIN"))
exception.PanicIfNeeded(err)

mongoPoolMax, err := strconv.Atoi(configuration.Get("MONGO_POOL_MAX"))
exception.PanicIfNeeded(err)

mongoMaxIdleTime, err := strconv.Atoi(configuration.Get("MONGO_MAX_IDLE_TIME_SECOND"))
exception.PanicIfNeeded(err)

option := options.Client().
ApplyURI(configuration.Get("MONGO_URI")).
SetMinPoolSize(uint64(mongoPoolMin)).
SetMaxPoolSize(uint64(mongoPoolMax)).
SetMaxConnIdleTime(time.Duration(mongoMaxIdleTime) * time.Second)

client, err := mongo.NewClient(option)
exception.PanicIfNeeded(err)

err = client.Connect(ctx)
Expand Down

0 comments on commit 4557dce

Please sign in to comment.