test(utils): 添加事件驱动模型测试
- 在 sqrt_test.go 中添加了 fastSqr1 测试函数,用于测试事件驱动模型 - 新增了 Event 和 Uint32AsyncEvent 类型用于测试 - 更新了 go.work、go.mod 和
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
package orders
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/badu/bus"
|
||||
"github.com/badu/bus/test_scenarios/request-reply-with-cancellation/events"
|
||||
)
|
||||
|
||||
type Order struct {
|
||||
ID int
|
||||
ProductIDs []int
|
||||
}
|
||||
|
||||
type RepositoryImpl struct {
|
||||
calls int
|
||||
}
|
||||
|
||||
func NewRepository() RepositoryImpl {
|
||||
result := RepositoryImpl{}
|
||||
bus.Sub(result.OnCreateOrder)
|
||||
return result
|
||||
}
|
||||
|
||||
func (r *RepositoryImpl) OnCreateOrder(event events.CreateOrderEvent) {
|
||||
defer func() {
|
||||
r.calls++
|
||||
}()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-time.After(4 * time.Second):
|
||||
event.NewOrder = &events.NewOrder{ID: r.calls}
|
||||
event.State.Close()
|
||||
return
|
||||
case <-event.State.Ctx.Done():
|
||||
event.State.Close()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package orders
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/badu/bus"
|
||||
"github.com/badu/bus/test_scenarios/request-reply-with-cancellation/events"
|
||||
)
|
||||
|
||||
type ServiceImpl struct {
|
||||
}
|
||||
|
||||
func NewService() ServiceImpl {
|
||||
result := ServiceImpl{}
|
||||
return result
|
||||
}
|
||||
|
||||
func (s *ServiceImpl) CreateOrder(ctx context.Context, productIDs []int) (*Order, error) {
|
||||
event := events.CreateOrderEvent{State: events.NewEventState(ctx), ProductIDs: productIDs, NewOrder: &events.NewOrder{}}
|
||||
bus.Pub(event)
|
||||
<-event.State.Done
|
||||
|
||||
if event.NewOrder != nil && event.State.Error == nil {
|
||||
return &Order{ID: event.NewOrder.ID, ProductIDs: productIDs}, nil
|
||||
}
|
||||
|
||||
return nil, event.State.Error
|
||||
}
|
||||
Reference in New Issue
Block a user