github.com/songzhibin97/gkit@v1.2.13/window/init.go (about)

     1  package window
     2  
     3  import (
     4  	"context"
     5  	"sync/atomic"
     6  	"time"
     7  
     8  	"github.com/songzhibin97/gkit/options"
     9  )
    10  
    11  // SetSize 设置大小
    12  func SetSize(size uint) options.Option {
    13  	return func(c interface{}) {
    14  		c.(*conf).size = size
    15  	}
    16  }
    17  
    18  // SetInterval 设置间隔时间
    19  func SetInterval(interval time.Duration) options.Option {
    20  	return func(c interface{}) {
    21  		c.(*conf).interval = interval
    22  	}
    23  }
    24  
    25  // SetContext 设置context
    26  func SetContext(context context.Context) options.Option {
    27  	return func(c interface{}) {
    28  		c.(*conf).ctx = context
    29  	}
    30  }
    31  
    32  // NewWindow 实例化
    33  func NewWindow(options ...options.Option) SlidingWindow {
    34  	w := Window{
    35  		// 默认值:
    36  		conf: conf{
    37  			size:     5,
    38  			interval: time.Second,
    39  			ctx:      context.Background(),
    40  		},
    41  	}
    42  	for _, option := range options {
    43  		option(&w.conf)
    44  	}
    45  	w.buffer = make([]atomic.Value, w.size)
    46  	for i := uint(0); i < w.size; i++ {
    47  		w.buffer[i].Store(make(map[string]uint))
    48  	}
    49  	w.communication = make(chan Index, w.size)
    50  	w.ctx, w.cancel = context.WithCancel(w.ctx)
    51  	// 开启哨兵
    52  	go w.sentinel()
    53  	return &w
    54  }