forked from p93542168/wheat-cache
120 lines
1.5 KiB
Go
120 lines
1.5 KiB
Go
package pkg
|
|
|
|
import "time"
|
|
|
|
type Value interface {
|
|
Get(key string) interface{}
|
|
Put(key string, val interface{}) error
|
|
}
|
|
|
|
type Data struct {
|
|
m map[string]interface{}
|
|
}
|
|
|
|
func (d *Data) Get(key string) interface{} {
|
|
return d.m[key]
|
|
}
|
|
|
|
func (d *Data) Put(key string, val interface{}) error {
|
|
d.m[key] = val
|
|
return nil
|
|
}
|
|
|
|
func NewData() *Data {
|
|
return &Data{
|
|
m: make(map[string]interface{}),
|
|
}
|
|
}
|
|
|
|
type MiddlewareConf struct {
|
|
Weight int
|
|
Middle Middleware
|
|
IsOut bool
|
|
}
|
|
|
|
type Driver struct {
|
|
conf []*MiddlewareConf
|
|
}
|
|
|
|
func (d *Driver) Stat(value Value) error {
|
|
for _, m := range d.conf {
|
|
m.Middle.Put(value) // 协程
|
|
value = m.Middle.Out()
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func NewDriver() *Driver {
|
|
return new(Driver)
|
|
}
|
|
|
|
func main() {
|
|
conf := []*MiddlewareConf{
|
|
{
|
|
Weight: 1,
|
|
Middle: NewM1(),
|
|
IsOut: false,
|
|
},
|
|
{
|
|
Weight: 2,
|
|
Middle: NewM2(),
|
|
IsOut: true,
|
|
},
|
|
}
|
|
|
|
driver := NewDriver()
|
|
driver.conf = conf
|
|
|
|
// 调用中间件驱动
|
|
val := NewData()
|
|
val.Put("2", 2)
|
|
|
|
driver.Stat(val)
|
|
|
|
}
|
|
|
|
type Middleware interface {
|
|
Put(val Value)
|
|
Out() Value
|
|
}
|
|
|
|
type M1 struct {
|
|
ch chan *Data
|
|
}
|
|
|
|
func (m *M1) Put(val Value) {
|
|
time.Sleep(200 * time.Second)
|
|
da := NewData()
|
|
da.Put("1", val)
|
|
m.ch <- da
|
|
}
|
|
|
|
func (m *M1) Out() Value {
|
|
return <-m.ch
|
|
}
|
|
|
|
func NewM1() *M1 {
|
|
return &M1{
|
|
make(chan *Data),
|
|
}
|
|
}
|
|
|
|
type M2 struct {
|
|
da Value
|
|
}
|
|
|
|
func (m *M2) Put(val Value) {
|
|
da := NewData()
|
|
m.da = da
|
|
}
|
|
|
|
func (m *M2) Out() Value {
|
|
m.da.Put("2", "plp")
|
|
return m.da
|
|
}
|
|
|
|
func NewM2() *M2 {
|
|
return &M2{}
|
|
}
|