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 90 91 92 93
|
package limiter
import ( "fmt" "go.uber.org/zap" "math/rand" "station.grab/src/common" "testing" "time" )
func Max(a int, b int) int {
if a > b { return a } return b } func RandomInt(n int) int { rand.Seed(time.Now().UnixNano()) v := rand.Intn(n) if v < 1 { v = 1 } return v }
type SampleJob struct { total int idx int key string }
func (s SampleJob) Run() (resp string, err error) {
v := fmt.Sprintf("job run: %d/%d, %v", s.idx, s.total, s.key) common.ZLogger.Info(v) time.Sleep(time.Second * 1)
return v, nil }
func TestLimiter_Execute(t *testing.T) {
fmt.Println("begin") total := 20 limiter := NewEasyLimiter(total, 5)
for i := 0; i < total; i++ { limiter.AddJob(&SampleJob{ total: total, idx: i, key: "test", }) }
chanSignal := make(chan interface{})
go func() { for { select { case result, ok := <-limiter.resultChan: common.ZLogger.Info("read from result chan ", zap.Any("result", result)) if !ok { common.ZLogger.Info("result通道关闭,退出当前goroutine") chanSignal<- 1 return } } } }()
limiter.Wait()
<-chanSignal
fmt.Println("done") }
func TestRandom(t *testing.T) { for i := 0; i < 20; i++ { fmt.Println(RandomInt(5)) }
}
|