main API

main

package

API reference for the main package.

S
struct

Notification

examples/basic/main.go:11-14
type Notification struct

Fields

Name Type Description
UserID int
Message string
F
function

main

examples/basic/main.go:16-79
func main()

{
	// In-memory broker (default) — no external dependencies.
	r := manager.New(
		manager.WithMaxRetries(3),
	)

	// Redis Streams broker (distributed, durable):
	//
	//   import (
	//       "github.com/mirkobrombin/go-relay/v2/pkg/broker"
	//       "github.com/redis/go-redis/v9"
	//   )
	//
	//   rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
	//   r := manager.New(
	//       manager.WithBroker(broker.NewRedisBroker(rdb,
	//           broker.WithGroup("my-workers"),
	//           broker.WithRedisMaxRetries(5),
	//           broker.WithClaimTimeout(60*time.Second),
	//       )),
	//   )

	// NATS JetStream broker (distributed, auto-stream creation):
	//
	//   import (
	//       "github.com/mirkobrombin/go-relay/v2/pkg/broker"
	//       "github.com/nats-io/nats.go"
	//       "github.com/nats-io/nats.go/jetstream"
	//   )
	//
	//   nc, _ := nats.Connect(nats.DefaultURL)
	//   js, _ := jetstream.New(nc)
	//   r := manager.New(
	//       manager.WithBroker(broker.NewNATSBroker(js,
	//           broker.WithNATSGroup("my-workers"),
	//           broker.WithMaxDeliver(5),
	//           broker.WithAckWait(45*time.Second),
	//       )),
	//   )

	manager.Register(r, "notify", func(ctx context.Context, n Notification) error {
		fmt.Printf("[Worker] Sending notification to User %d: %s\n", n.UserID, n.Message)
		time.Sleep(100 * time.Millisecond)
		return nil
	})

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	go func() {
		fmt.Println("Relay started. Waiting for jobs...")
		if err := r.Start(ctx); err != nil {
			panic(err)
		}
	}()

	fmt.Println("Enqueueing jobs...")
	_ = manager.Enqueue(ctx, r, "notify", Notification{UserID: 101, Message: "Hello World"})
	_ = manager.Enqueue(ctx, r, "notify", Notification{UserID: 102, Message: "Order Shipped"})
	_ = manager.Enqueue(ctx, r, "notify", Notification{UserID: 103, Message: "System Alert"})

	time.Sleep(1 * time.Second)
	fmt.Println("Done.")
}