在应用系统中,常见的的应用场景就是调用一个生成器:生成订单号,序列号,随机数等。
golang goroutine为这种需求提供了强大的武器。
1.简单的生成器
package main
import (
"fmt"
"math/rand"
)
func GenerateIntA()chan int {
ch := make(chan int ,10)
go func(){
for {
ch<-rand.Int()
}
}()
return ch
}
func main(){
ch := GenerateIntA()
fmt.Println(<-ch)
fmt.Println(<-ch)
}
2.叠加增强型资源生成器
可以使用多路复用技术进行堆积叠加,增加服务能力 可以使用缓冲chan增加服务能力
package main
import (
"fmt"
"math/rand"
)
func GenerateIntA() chan int {
ch := make(chan int, 10)
go func() {
for {
ch <- rand.Int()
}
}()
return ch
}
func GenerateIntB() chan int {
ch := make(chan int, 10)
go func() {
for {
ch <- rand.Int()
}
}()
return ch
}
func GenerateInt() chan int {
ch := make(chan int, 20)
go func() {
for {
select {
case ch <- <-GenerateIntA():
case ch <- <-GenerateIntB():
}
}
}()
return ch
}
func main() {
ch := GenerateInt()
for i := 0; i < 100; i++ {
fmt.Println(<-ch)
}
}
3.有时我们希望生成器能够自动的退出,这时可以使用golang channel的
Close channel to broadcast 机制实现:
package main
import (
"fmt"
"math/rand"
)
func GenerateIntA(done chan struct{})chan int {
ch := make(chan int )
go func(){
Lable:
for {
select {
case ch<-rand.Int():
case <-done:
break Lable
}
}
close(ch)
}()
return ch
}
func main(){
done :=make(chan struct{})
ch := GenerateIntA(done)
fmt.Println(<-ch)
fmt.Println(<-ch)
close(done)
fmt.Println(<-ch)
fmt.Println(<-ch)
fmt.Println(<-ch)
fmt.Println(<-ch)
}
4.可以更牛逼点,既要并发、缓冲,又有通知的生成器:
package main
import (
"fmt"
"math/rand"
)
func GenerateIntA(done chan struct{}) chan int {
ch := make(chan int, 5)
go func() {
Lable:
for {
select {
case ch <- rand.Int():
case <-done:
break Lable
}
}
close(ch)
}()
return ch
}
func GenerateIntB(done chan struct{}) chan int {
ch := make(chan int, 10)
go func() {
Lable:
for {
select {
case ch <- rand.Int():
case <-done:
break Lable
}
}
close(ch)
}()
return ch
}
func GenerateInt(done chan struct{}) chan int {
ch := make(chan int)
send := make(chan struct{})
go func() {
Lable:
for {
select {
case ch <- <-GenerateIntA(send):
case ch <- <-GenerateIntB(send):
case <-done:
send <- struct{}{}
send <- struct{}{}
break Lable
}
}
close(ch)
}()
return ch
}
func main() {
done := make(chan struct{})
ch := GenerateInt(done)
for i := 0; i < 10; i++ {
fmt.Println(<-ch)
}
done <- struct{}{}
for i := 0; i < 10; i++ {
v := <-ch
if v == 0 {
return
}
fmt.Println(<-ch)
}
}
以下给大家整理一个ID生成器
package main
import (
"net/http"
"runtime"
"strconv"
"strings"
"time"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
// 开始启动监听key变化监听
go watch()
bind, b := config.Get("", "bind")
if !b {
bind = ":3002"
}
http.HandleFunc("/", requestID)
http.HandleFunc("/* ", requestID)
// 开始http处理
err := http.ListenAndServe(bind, nil)
if err != nil {
panic(err)
}
}
// 处理用户的网络请求
func requestID(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
name := r.Form.Get("name")
if name == "" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("name can`t be empty"))
return
}
num := 1
if tmpNum := r.Form.Get("num"); tmpNum != "" {
tmpNum2, err := strconv.Atoi(tmpNum)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("num not a int"))
return
}
num = tmpNum2
}
if tmpMaxRequestNum, b := config.Get("", "max_request_num"); b {
if tmpMaxRequestNumInt, err := strconv.Atoi(tmpMaxRequestNum); err == nil {
if num > tmpMaxRequestNumInt {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("num more than max request id num"))
return
}
} else {
errMessage := err.Error()
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(errMessage))
return
}
}
if value, exists := watchList[name]; exists {
w.WriteHeader(http.StatusOK)
if num > 1 {
arr := make([]string, 0)
for i := 0; i < num; i++ {
// 从通信队列中获取数据时添加5秒的超时时间
select {
case rs := <-value:
arr = append(arr, strconv.FormatInt(rs, 10))
case <-time.After(5 * time.Second):
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("server create id timeout"))
}
}
w.Write([]byte(strings.Join(arr, ",")))
} else {
// 从通信队列中获取数据时添加5秒的超时时间
select {
case rs := <-value:
w.Write([]byte(strconv.FormatInt(rs, 10)))
case <-time.After(5 * time.Second):
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("server create id timeout"))
}
}
return
}
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("name can`t found"))
}
百度网盘:
链接: https://pan.baidu.com/s/1K-cAKq0FXbDwsLmngcGU5w 提取码: i8dk
参考资料:
Go语言生成器
https://blog.csdn.net/u010412301/article/details/79559431
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有