streamx.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package redisx
  2. import (
  3. "context"
  4. "time"
  5. "github.com/redis/go-redis/v9"
  6. )
  7. // Stream(流)封装
  8. // 添加消息
  9. func XAdd(ctx context.Context, stream string, values map[string]interface{}) (string, error) {
  10. return getClient().XAdd(ctx, &redis.XAddArgs{
  11. Stream: stream,
  12. Values: values,
  13. }).Result()
  14. }
  15. // 读取消息
  16. func XRead(ctx context.Context, streams map[string]string, count int64) ([]redis.XStream, error) {
  17. args := &redis.XReadArgs{
  18. Streams: flattenStreams(streams),
  19. Count: count,
  20. Block: 0,
  21. }
  22. return getClient().XRead(ctx, args).Result()
  23. }
  24. // 创建消费者组
  25. func XGroupCreate(ctx context.Context, stream, group, start string) error {
  26. return getClient().XGroupCreateMkStream(ctx, stream, group, start).Err()
  27. }
  28. // 从消费者组读取
  29. func XReadGroup(ctx context.Context, group, consumer string, streams map[string]string, count int64) ([]redis.XStream, error) {
  30. args := &redis.XReadGroupArgs{
  31. Group: group,
  32. Consumer: consumer,
  33. Streams: flattenStreams(streams),
  34. Count: count,
  35. Block: 5 * time.Second,
  36. }
  37. return getClient().XReadGroup(ctx, args).Result()
  38. }
  39. // 确认消息
  40. func XAck(ctx context.Context, stream, group string, ids ...string) error {
  41. return getClient().XAck(ctx, stream, group, ids...).Err()
  42. }
  43. func flattenStreams(m map[string]string) []string {
  44. arr := make([]string, 0, len(m)*2)
  45. for k, v := range m {
  46. arr = append(arr, k, v)
  47. }
  48. return arr
  49. }