一个go的简单协程
Posted 菜鸟的地盘
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一个go的简单协程相关的知识,希望对你有一定的参考价值。
package main
import(
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"time"
)
type User struct{
ID uint32 `json:"id"`
// Username 用户名 [手机号]
Username string `json:"username"`
// Wxid 微信ID [unionid]
Wxid string `json:"unionid"`
// Openid 微信ID [openid]
Openid string `json:"openid"`
}
func main(){
ch := make(chan User, 100000)
out := make(chan string, 100000)
index := get_data(ch, 1, 100000)
go request_test(out, ch)
go request_test(out, ch)
go request_test(out, ch)
go request_test(out, ch)
go request_test(out, ch)
go request_test(out, ch)
go request_test(out, ch)
go request_test(out, ch)
go request_test(out, ch)
go request_test(out, ch)
go request_test(out, ch)
go request_test(out, ch)
fmt.Println(index)
for i := range out {
fmt.Println(i)
}
}
func get_data(ch chan User, firts int, limit int) int{
db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:33060)/test")
checkErr(err)
var index = 0;
defer db.Close()
//查询数据
rows, err := db.Query("SELECT id, username, wxid, openid FROM xt_user limit ?,?", firts, limit)
checkErr(err)
for rows.Next() {
var user User
rows.Scan(&user.ID, &user.Username, &user.Wxid, &user.Openid)
index = int(user.ID)
ch <- user
}
return index
}
func request_test(out chan string, ch chan User){
for it := range ch {
m := map[string]string{
"mobile": it.Username,
"unionId":it.Wxid,
"openId": "",
"code": "1235",
}
url := "“
res := Post(url, m, "application/json")
out <- res
}
}
// 发送POST请求
// url: 请求地址
// data: POST请求提交的数据
// contentType: 请求体格式,如:application/json
// content: 请求放回的内容
func Post(url string, data interface{}, contentType string) string {
// 超时时间:5秒
client := &http.Client{Timeout: 5 * time.Second}
jsonStr, _ := json.Marshal(data)
resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonStr))
if err != nil {
panic(err)
}
defer resp.Body.Close()
result, _ := ioutil.ReadAll(resp.Body)
return string(result)
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
以上是关于一个go的简单协程的主要内容,如果未能解决你的问题,请参考以下文章