前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Golang语言情怀-第15期 Go 语言设计模式 创建模式-生成器

Golang语言情怀-第15期 Go 语言设计模式 创建模式-生成器

作者头像
李海彬
发布2021-01-21 17:21:31
3370
发布2021-01-21 17:21:31
举报
文章被收录于专栏:Golang语言社区Golang语言社区

在应用系统中,常见的的应用场景就是调用一个生成器:生成订单号,序列号,随机数等。

golang goroutine为这种需求提供了强大的武器。

1.简单的生成器

代码语言:javascript
复制
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增加服务能力

代码语言:javascript
复制
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 机制实现:

代码语言:javascript
复制
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.可以更牛逼点,既要并发、缓冲,又有通知的生成器:

代码语言:javascript
复制
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生成器

代码语言:javascript
复制
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

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-01-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Golang语言情怀 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档