-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_factory_test.go
89 lines (71 loc) · 2.06 KB
/
example_factory_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package queue_test
import (
"context"
"fmt"
"time"
queue "github.com/DoNewsCode/core-queue"
"github.com/DoNewsCode/core"
"github.com/DoNewsCode/core/otredis"
"github.com/knadh/koanf/parsers/json"
"github.com/knadh/koanf/providers/rawbytes"
"github.com/oklog/run"
)
type MockFactoryData struct {
Value string
}
type MockFactoryListener struct{}
func (m MockFactoryListener) Listen() queue.Job {
return queue.JobFrom(MockFactoryData{})
}
func (m MockFactoryListener) Process(_ context.Context, Job queue.Job) error {
fmt.Println(Job.Data().(MockFactoryData).Value)
return nil
}
// bootstrapMetrics is normally done when bootstrapping the framework. We mimic it here for demonstration.
func bootstrapFactories() *core.C {
const sampleConfig = "{\"log\":{\"level\":\"error\"},\"queue\":{\"default\":{\"parallelism\":2},\"myQueue\":{\"parallelism\":1}}}"
// Make sure redis is running at localhost:6379
c := core.New(
core.WithConfigStack(rawbytes.Provider([]byte(sampleConfig)), json.Parser()),
)
// Add ConfProvider
c.ProvideEssentials()
c.Provide(otredis.Providers())
c.Provide(queue.Providers())
return c
}
// serveMetrics normally lives at serve command. We mimic it here for demonstration.
func serveFactories(c *core.C, duration time.Duration) {
var g run.Group
c.ApplyRunGroup(&g)
// cancel the run group after some time, so that the program ends. In real project, this is not necessary.
ctx, cancel := context.WithTimeout(context.Background(), duration)
defer cancel()
g.Add(func() error {
<-ctx.Done()
return nil
}, func(err error) {
cancel()
})
err := g.Run()
if err != nil {
panic(err)
}
}
func Example_factory() {
c := bootstrapFactories()
c.Invoke(func(maker queue.DispatcherMaker) {
dispatcher, err := maker.Make("myQueue")
if err != nil {
panic(err)
}
// Subscribe
dispatcher.Subscribe(MockFactoryListener{})
// Trigger an Job
evt := queue.JobFrom(MockFactoryData{Value: "hello world"})
_ = dispatcher.Dispatch(context.Background(), queue.Adjust(evt))
})
serveFactories(c, 1*time.Second)
// Output:
// hello world
}