Example_subscription demonstrates the use of client subscriptions to receive events containing information about worked jobs.
()
| 40 | // Example_subscription demonstrates the use of client subscriptions to receive |
| 41 | // events containing information about worked jobs. |
| 42 | func Example_subscription() { |
| 43 | ctx := context.Background() |
| 44 | |
| 45 | dbPool, err := pgxpool.New(ctx, riversharedtest.TestDatabaseURL()) |
| 46 | if err != nil { |
| 47 | panic(err) |
| 48 | } |
| 49 | defer dbPool.Close() |
| 50 | |
| 51 | workers := river.NewWorkers() |
| 52 | river.AddWorker(workers, &SubscriptionWorker{}) |
| 53 | |
| 54 | riverClient, err := river.NewClient(riverpgxv5.New(dbPool), initTestConfig(ctx, dbPool, &river.Config{ |
| 55 | Logger: slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.Level(9), ReplaceAttr: slogutil.NoLevelTime})), // Suppress logging so example output is cleaner (9 > slog.LevelError). |
| 56 | Queues: map[string]river.QueueConfig{ |
| 57 | river.QueueDefault: {MaxWorkers: 100}, |
| 58 | }, |
| 59 | Workers: workers, |
| 60 | })) |
| 61 | if err != nil { |
| 62 | panic(err) |
| 63 | } |
| 64 | |
| 65 | // Subscribers tell the River client the kinds of events they'd like to receive. |
| 66 | completedChan, completedSubscribeCancel := riverClient.Subscribe(river.EventKindJobCompleted) |
| 67 | defer completedSubscribeCancel() |
| 68 | |
| 69 | // Multiple simultaneous subscriptions are allowed. |
| 70 | failedChan, failedSubscribeCancel := riverClient.Subscribe(river.EventKindJobFailed) |
| 71 | defer failedSubscribeCancel() |
| 72 | |
| 73 | otherChan, otherSubscribeCancel := riverClient.Subscribe(river.EventKindJobCancelled, river.EventKindJobSnoozed) |
| 74 | defer otherSubscribeCancel() |
| 75 | |
| 76 | if err := riverClient.Start(ctx); err != nil { |
| 77 | panic(err) |
| 78 | } |
| 79 | |
| 80 | // Insert one job for each subscription above: one to succeed, one to fail, |
| 81 | // and one that's cancelled that'll arrive on the "other" channel. |
| 82 | _, err = riverClient.Insert(ctx, SubscriptionArgs{}, nil) |
| 83 | if err != nil { |
| 84 | panic(err) |
| 85 | } |
| 86 | _, err = riverClient.Insert(ctx, SubscriptionArgs{Fail: true}, nil) |
| 87 | if err != nil { |
| 88 | panic(err) |
| 89 | } |
| 90 | _, err = riverClient.Insert(ctx, SubscriptionArgs{Cancel: true}, nil) |
| 91 | if err != nil { |
| 92 | panic(err) |
| 93 | } |
| 94 | |
| 95 | waitForJob := func(subscribeChan <-chan *river.Event) { |
| 96 | select { |
| 97 | case event := <-subscribeChan: |
| 98 | if event == nil { |
| 99 | fmt.Printf("Channel is closed\n") |
nothing calls this directly
no test coverage detected
searching dependent graphs…