Created
July 5, 2014 08:18
-
-
Save reterVision/7520e5f162c8480e9126 to your computer and use it in GitHub Desktop.
A trivial program that uses goroutine to insert records into Postgres.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Original idea from | |
http://www.acloudtree.com/how-to-shove-data-into-postgres-using-goroutinesgophers-and-golang/ | |
*/ | |
package main | |
import ( | |
"log" | |
"time" | |
"os" | |
"fmt" | |
"database/sql" | |
_ "github.com/lib/pq" | |
) | |
func main() { | |
fmt.Printf("StartTime: %v\n", time.Now()) | |
var ( | |
sStmt string = "insert into test (gopher_id, created) values ($1, $2)" | |
gophers int = 10 | |
entries int = 10000 | |
) | |
finishChan := make(chan int) | |
for i := 0; i < gophers; i++ { | |
go func(c chan int) { | |
db, err := sql.Open("postgres", "host=localhost dbname=testdb sslmode=disable") | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer db.Close() | |
stmt, err := db.Prepare(sStmt) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer stmt.Close() | |
for j := 0; j < entries; j++ { | |
res, err := stmt.Exec(j, time.Now()) | |
if err != nil || res == nil { | |
log.Fatal(err) | |
} | |
} | |
c <- 1 | |
}(finishChan) | |
} | |
finishedGophers := 0 | |
finishLoop := false | |
for { | |
if finishLoop { | |
break | |
} | |
select { | |
case n := <-finishChan: | |
finishedGophers += n | |
if finishedGophers == 10 { | |
finishLoop = true | |
} | |
} | |
} | |
fmt.Printf("StopTime: %v\n", time.Now()) | |
} |
Hello !
Same question here. For what I can see It generate an error : "read tcp [::1]:61029->[::1]:5432: read: connection reset by peer"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@reterVision thanks good example! But, what if we use only one open database, and multiple http methods read/write, how it would be?