Created
November 7, 2019 06:41
-
-
Save Allenxuxu/0cc5539e9329ffddf28cfdb59966bfbd to your computer and use it in GitHub Desktop.
Redis MQ(消费者/生产者模式)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package redismq | |
import ( | |
"time" | |
"github.com/go-redis/redis" | |
) | |
// RedisMQ Redis list 封装的消费者/生产者模式 先进先出 MQ | |
type RedisMQ struct { | |
client *redis.Client | |
} | |
// New RedisMQ | |
func New(host, password string) (*RedisMQ, error) { | |
client := redis.NewClient(&redis.Options{ | |
Network: "tcp", | |
Addr: host, | |
Password: password, | |
IdleTimeout: 240 * time.Second, | |
MinIdleConns: 16, | |
DB: 0, // use default DB | |
}) | |
_, err := client.Ping().Result() | |
if err != nil { | |
return nil, err | |
} | |
return &RedisMQ{client: client}, nil | |
} | |
// Push 发送到 指定 topic | |
func (r *RedisMQ) Push(topic string, values ...string) (int64, error) { | |
return r.client.LPush(topic, values).Result() | |
} | |
// BlockSub 阻塞等到 topic 下的消息 | |
func (r *RedisMQ) BlockSub(topic string) (string, error) { | |
ret, err := r.client.BRPop(0, topic).Result() | |
if err != nil { | |
return "", err | |
} | |
return ret[1], nil | |
} | |
func (r *RedisMQ) clear(topic string) error { | |
return r.client.LTrim(topic, 0, -1).Err() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment