Go Channel读写卡在无限循环中

时间:2016-07-26 10:02:02

标签: go channel beego

首先,我想制作长轮询通知系统。更具体地说,我将发出http请求,只有在地图频道为true时才会返回响应。

这是我使用的代码块:

var MessageNotification = make(map[string]chan bool, 10)

func GetNotification(id int, timestamp int) notification {
    <-MessageNotification["1"]

    var chat_services []*models.Chat_service
    o := orm.NewOrm()

    _, err := o.QueryTable("chat_service").Filter("Sender__id", id).RelatedSel().All(&chat_services)

    if err != nil {
        return notification{Status: false}
    }
    return notification{Status: true, MessageList: chat_services}
}

func SetNotification(id int) {
    MessageNotification[strconv.Itoa(id)] <- true
}

这是控制器块:

func (c *ChatController) Notification() {

data := chat.GetNotification(1,0)

c.Data["json"] = data
c.ServeJSON()

  }


func (c *ChatController) Websocket(){


    chat.SetNotification(1)

    c.Data["json"] = "test"
    c.ServeJSON();

}

为测试创建的函数名称和变量。

没有发生错误。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

您没有创建频道。

var MessageNotification = make(map[string]chan bool, 10)

此行生成容量为10的地图,但您未在地图中创建实际的频道。结果,`SetNotification [&#34; 1&#34;]是一个nil通道,并且无限制地在nil通道上发送和接收。

你需要输入

MessageNotification["1"] = make(chan bool)

如果需要,你可以包括一个大小(我预感你的&#34; 10&#34;在地图中make应该是该频道的缓冲)。这甚至可以有条件地完成:

func GetNotification(id int, timestamp int) notification {
    if _, ok := MessageNotification["1"]; !ok { // if map does not contain that key
        MessageNotification["1"] = make(chan bool, 10)
    }

    <-MessageNotification["1"]
    // ...
}

func SetNotification(id int) {
    if _, ok := MessageNotification[strconv.Itoa(id)]; !ok { // if map does not contain that key
        MessageNotification[strconv.Itoa(id)] = make(chan bool, 10)
    }

    MessageNotification[strconv.Itoa(id)] <- true
}

这样,尝试访问频道的第一个位置会将其添加到地图并正确创建频道,因此发送和接收频道实际上将起作用。