Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
H
HARMONY-experimental-branch
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Requirements
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Locked files
Build
Pipelines
Jobs
Pipeline schedules
Test cases
Artifacts
Deploy
Releases
Package registry
Container Registry
Model registry
Operate
Environments
Terraform modules
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Code review analytics
Issue analytics
Insights
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
Robin Korfmann
HARMONY-experimental-branch
Commits
1f116241
Commit
1f116241
authored
1 month ago
by
Cecile Ntsama
Browse files
Options
Downloads
Patches
Plain Diff
add MongoManager for centralized MongoDB connection handling
parent
742718fc
No related branches found
No related tags found
1 merge request
!4
merge dev to main
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
src/Project/mongodb.go
+97
-0
97 additions, 0 deletions
src/Project/mongodb.go
with
97 additions
and
0 deletions
src/Project/mongodb.go
0 → 100644
+
97
−
0
View file @
1f116241
package
project
import
(
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// MongoManager handles MongoDB connection management and database operations
// This struct encapsulates the MongoDB client and database references
// It provides a centralized way to manage database connections throughout the application
type
MongoManager
struct
{
client
*
mongo
.
Client
// The MongoDB client for connection management
db
*
mongo
.
Database
// The specific database instance for this application
}
// NewMongoManager creates and initializes a new MongoDB connection manager
// This function establishes a connection to MongoDB with optimized settings
// and returns a manager instance that can be used throughout the application
func
NewMongoManager
(
uri
,
dbName
string
)
(
*
MongoManager
,
error
)
{
log
.
Printf
(
"INFO: Connecting to MongoDB at %s, database: %s"
,
uri
,
dbName
)
// Configure MongoDB client options for optimal performance
clientOptions
:=
options
.
Client
()
.
ApplyURI
(
uri
)
// Set connection pool parameters for handling concurrent requests efficiently
// MaxPoolSize: Maximum number of connections in the pool (100 connections)
// This allows the application to handle many concurrent database operations
clientOptions
.
SetMaxPoolSize
(
100
)
// MinPoolSize: Minimum number of connections to maintain (10 connections)
// This ensures quick response times by keeping connections ready
clientOptions
.
SetMinPoolSize
(
10
)
// MaxConnIdleTime: How long idle connections stay open (30 seconds)
// This balances resource usage with connection availability
clientOptions
.
SetMaxConnIdleTime
(
30
*
time
.
Second
)
log
.
Printf
(
"DEBUG: MongoDB connection pool configured - max: 100, min: 10, idle timeout: 30s"
)
// Attempt to create a connection to MongoDB using the configured options
client
,
err
:=
mongo
.
Connect
(
context
.
TODO
(),
clientOptions
)
if
err
!=
nil
{
log
.
Printf
(
"ERROR: Failed to connect to MongoDB: %v"
,
err
)
return
nil
,
fmt
.
Errorf
(
"failed to connect to MongoDB: %w"
,
err
)
}
log
.
Println
(
"DEBUG: MongoDB client created, testing connection..."
)
// Test the connection by pinging the MongoDB server
// This ensures that the connection is actually working before proceeding
ctx
,
cancel
:=
context
.
WithTimeout
(
context
.
Background
(),
10
*
time
.
Second
)
defer
cancel
()
// Ensure the context is cleaned up after the ping
if
err
:=
client
.
Ping
(
ctx
,
nil
);
err
!=
nil
{
log
.
Printf
(
"ERROR: MongoDB ping failed: %v"
,
err
)
return
nil
,
fmt
.
Errorf
(
"failed to ping MongoDB: %w"
,
err
)
}
log
.
Printf
(
"INFO: Successfully connected to MongoDB database '%s'"
,
dbName
)
// Return a configured MongoManager instance
return
&
MongoManager
{
client
:
client
,
// Store the client for connection management
db
:
client
.
Database
(
dbName
),
// Store the database reference for operations
},
nil
}
// GetDatabase returns the MongoDB database instance for performing operations
// This method provides access to the database for repositories and other components
// that need to interact with MongoDB collections
func
(
m
*
MongoManager
)
GetDatabase
()
*
mongo
.
Database
{
log
.
Printf
(
"DEBUG: Returning database instance: %s"
,
m
.
db
.
Name
())
return
m
.
db
}
// Close gracefully shuts down the MongoDB connection
// This method should be called when the application is shutting down
// to ensure all connections are properly closed and resources are released
func
(
m
*
MongoManager
)
Close
()
error
{
log
.
Println
(
"INFO: Closing MongoDB connection..."
)
// Disconnect the MongoDB client using a background context
// This ensures that ongoing operations can complete before disconnection
err
:=
m
.
client
.
Disconnect
(
context
.
Background
())
if
err
!=
nil
{
log
.
Printf
(
"ERROR: Failed to close MongoDB connection: %v"
,
err
)
return
err
}
log
.
Println
(
"INFO: MongoDB connection closed successfully"
)
return
nil
}
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment