gomodule / redigo

Go client for Redis
Apache License 2.0
9.76k stars 1.25k forks source link

PoolConn's Close will not stop the block commands like BLPOP #617

Closed chenjie199234 closed 2 years ago

chenjie199234 commented 2 years ago

example

pool := &redis.Pool{}
c,_:=pool.GetContext(context.Background())
go func(){
        time.sleep(time.second)
        c.Close()//this will not cause the BLPOP return
}()
c.(redis.ConnWithTimeout).DoWithTimeout(0,"BLPOP","testlist",0)
stevenh commented 2 years ago

You could use DoContext with a cancellable context to enable this flow.

p := &redis.Pool{}
c := p.Get()
defer p.Close()

cc, ok := c.(redis.ConnWithContext)
if !ok {
      // TODO: Handle
     return errors.New("connection doesn't support context")
}

ctx, cancel := context.WithCancel(context.Background())

go func() {
      defer cancel()
      time.Sleep(time.Second)
}()

v, err := cc.DoContext(ctx, "BLPOP","testlist",0)
if err != nil {
     if errors.Is(err, context.Canceled) {
         // TODO: Handle cancelled
         fmt.Println(err)
     }
    return err
}

// TODO: process data
fmt.Println(v)