golang用多个协程,生成随机字符串,插入数据库

之前都是用php在cli下去跑,生成随机字符串,由于php单线程 插入速度快不起来
利用golang起很多个协程一起去跑,就可以达到快速插入数据库的目的

demo

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "math/rand"
    "os"
    "strconv"
    "time"
)
var xiecheng int
var num int
var total int
var db *sql.DB
var success_total int
var error_total int
var start_time int64
var end_time int64
func main(){
    defer func() {
        if err := recover(); err != nil {
            fmt.Println(err)
        }
    }()
    start_time = time.Now().Unix()
    fmt.Println("生成总数=协程数*每个协程生成的数量")
    fmt.Println("请输入要启用的协程数")
    fmt.Scanln(&xiecheng)
    if xiecheng == 0{
        fmt.Println("请输入正确的协程数")
        return
    }
    fmt.Println("请输入每个协程生成的数量")
    fmt.Scanln(&num)
    if num == 0{
        fmt.Println("请输入正确的数量")
        return
    }
    total = num*xiecheng
    if xiecheng == 0{
        fmt.Println("请输入正确的数量 需大于100")
        return
    }
    rand.Seed(time.Now().UnixNano())
    DB,_ := sql.Open("mysql","数据库用户名:密码@tcp(主机名:端口号)/数据库名?charset=utf8")
    db = DB
    for i:=0;i<xiecheng;i++{
        go insert()
    }
    select{}
}
func randstr(lens int)string{
    var str string
    strpol := "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    for i:=0;i<lens;i++ {
        num := rand.Intn(len(strpol)-1)
        str = str + strpol[num:num+1]
    }
    return str
}
func insert(){
    var success int
    var error int
    for i:=0;i<num;i++{
        key := randstr(8)
        sql_str := "insert into code(`key`,create_time,update_time) values('" + key + "','" + strconv.Itoa(int(time.Now().Unix())) + "','" + strconv.Itoa(int(time.Now().Unix())) + "')"
        _, err := db.Exec(sql_str)
        //_, err := db.Query(sql)
        if err == nil{
            success++
            fmt.Printf("生成成功:%s\n",key)
        }else{
            error++
            fmt.Println(err)
            fmt.Println(sql_str)
            fmt.Printf("生成失败:%s\n",key)
        }
    }
    success_total += success
    error_total += error
    if success_total + error_total == total{
        end_time = time.Now().Unix()
        fmt.Printf("\n生成总数:%d\n成功数:%d\n失败数:%d\n开始时间:%s\n结束时间:%s\n耗时:%d秒\n",total,success_total,error_total,time.Unix(start_time, 0).Format("2006-01-02 15:04:05"),time.Unix(end_time, 0).Format("2006-01-02 15:04:05"),end_time-start_time)
        os.Exit(0)
    }
}
Last modification:December 4th, 2019 at 02:57 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment

简爱博客