douliao8318 2018-04-26 10:14
浏览 34

结束Redigo进程

I'm working on a chat server and am using redigo in order to publish messages across many web socket connections. I have a go routine that (per user connection) opens a connection to redis, subscribes to some channels and waits for a message. Waiting for this message -

msg := psc.Receive()

is a blocking operation in the fact that any code after the receive function will not run until a message comes in. However I would like to be able to watch for context -

ctx.Done()

or the like. Is this achievable using a select, or is there a more idiomatic way of writing this? I am attempting to do this as in the current implementation this function is run as a go routine, and if the web session ends I would like to end the redis connection and finish the go routine.

func relayRedisMessages (ctx context.Context, ws *websocket.Conn, rc []string) {

    c, err := redis.Dial("tcp", "localhost:6379")
    if err != nil {
        log.Println(err)
        return
    }
    defer c.Close()

    psc := redis.PubSubConn{c}

    for _, channel := range rc {
        psc.Subscribe(channel)
    }

    for {
        msg := psc.Receive()
        // Write message to websocket
        var msg Message
        json.Unmarshal(v.Data, &msg)
        err = ws.WriteJSON(msg)
        if err != nil {
            log.Println(err)
            break
        }
    }
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
    • ¥15 Vue3地图和异步函数使用
    • ¥15 C++ yoloV5改写遇到的问题
    • ¥20 win11修改中文用户名路径
    • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
    • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
    • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
    • ¥15 帮我写一个c++工程
    • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
    • ¥15 关于smbclient 库的使用