Details
-
Task
-
Resolution: Done
-
Major - P3
-
None
-
None
-
None
-
None
-
mongo-go-driver v1.3.4
Description
I set the ConnectTimeout, but it looks like no working.
This is my code:
|
|
type Conf struct {
|
Host string
|
Port string
|
DbName string
|
ConnectTimeout time.Duration
|
SocketTimeout time.Duration
|
MaxPoolSize uint64
|
MinPoolSize uint64
|
Direct bool
|
}
|
|
|
func Init() {
|
opts := conf2options(e.Conf)
|
c, err := mongo.Connect(NewCtx(e.Conf.ConnectTimeout),
|
opts.ApplyURI(fmt.Sprintf("mongodb://%s:%s/%s", e.Conf.Host, e.Conf.Port, e.Conf.DbName))) |
if err != nil { |
return err |
}
|
|
err = c.Ping(context.Background(), readpref.Primary())
|
if err != nil { |
return err |
}
|
}
|
func conf2options(conf *Conf) *options.ClientOptions {
|
return &options.ClientOptions{ |
ConnectTimeout: &conf.ConnectTimeout,
|
SocketTimeout: &conf.SocketTimeout,
|
MaxPoolSize: &conf.MaxPoolSize,
|
MinPoolSize: &conf.MinPoolSize,
|
Direct: &conf.Direct,
|
}
|
}
|
I set `ConnectTimeout = 10 * time.second`, but the test output:
--- FAIL: TestClient (30.00s) |
engine_test.go:9: server selection error: server selection timeout, current topology: { Type: Single, Servers: [{ Addr: 127.0.0.1:27017, Type: Unknown, State: Connected, Average RTT: 0, Last error: connection() : dial tcp 127.0.0.1:27017: connect: connection refused }, ] } |
FAIL
|
exit status 1 |
FAIL go.study.org/mongoDemo/mongoorg 30.005s |
It took 30 seconds, seems like default ConnectTimeout.
Then i use context.WithTimeout, it works.
func Init() {
|
opts := conf2options(e.Conf)
|
c, err := mongo.Connect(NewCtx(e.Conf.ConnectTimeout),
|
opts.ApplyURI(fmt.Sprintf("mongodb://%s:%s/%s", e.Conf.Host, e.Conf.Port, e.Conf.DbName))) |
if err != nil { |
return err |
}
|
|
ctx, _ := context.WithTimeout(context.Backgroud(), 10*time.Second) |
err = c.Ping(ctx, readpref.Primary())
|
if err != nil { |
return err |
}
|
}
|
the output:
--- FAIL: TestClient (10.00s) |
engine_test.go:9: context deadline exceeded |
FAIL
|
exit status 1 |
FAIL go.study.org/mongoDemo/mongoorg 10.006s |
I think I used it(options.ClientOptions.ConnectTimeout) in the wrong way
.But I can't found the true way.
Are there any way to make it works without context when used options.ClientOptions.ConnectTimeout?