SoFunction
Updated on 2025-03-01

Go+redis implements the detailed process of publishing and subscribing message queues

During the project, when implementing websockets, I don’t know where to write them properly. The client message received a certain level, and the remaining messages could not be received. The buffer size was modified, but the problem was still not solved. Later, because the project end period was relatively tight and there was no time to debug messages, I used the redis queue to temporarily save the messages, and the client polled to get the corresponding messages.

1. The producer publishes messages randomly and publishes them with rpush.
2. Consumers use lpop to subscribe to consume, and once there is no message, they will randomly hibernate.
The disadvantage of redis to do message queues: no persistence. Once the news is not consumed, it will be lost after it accumulates to a certain extent.

package main

import (
    "fmt"
    "time"
    "os"
    "strconv"
    "math/rand"
    "/gomodule/redigo/redis"
)

const RMQ string = "mqtest"

func producer() {
    redis_conn, err := ("tcp", "127.0.0.1:6379", ("hdiot"))
    if err != nil {
        (err)
        return
    }
    
    defer redis_conn.Close()
    
    (().UnixNano())

    var i = 1

    for {
        _,err = redis_conn.Do("rpush", RMQ, (i))
        if(err!=nil) {
            ("produce error")
            continue
        }
        ("produce element:%d", i)
        (((10))*)
        i++
    }
}

func consumer() {
    redis_conn, err := ("tcp", "127.0.0.1:6379", ("hdiot"))
    if err != nil {
        (err)
        return
    }
    
    defer redis_conn.Close()

    (().UnixNano())

    for {
        ele,err := (redis_conn.Do("lpop", RMQ))
        if(err != nil) {
            ("no  now")
            (((10))*)
        } else {
            ("cosume element:%s", ele)
        }
    }
}

func main() {
    list := 
    if(list[1] == "pro") {
        go producer()
    } else if (list[1] == "con") {
        go consumer()
    }
    for {
        ((10000)*)
    }
}

This is the article about the detailed process of go+redis to implement message queue publishing and subscription. For more related go redis message queue content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!