mirror of
https://github.com/zeromicro/go-zero.git
synced 2026-05-07 15:10:01 +08:00
feat(redis): add redis command for getex (#5323)
This commit is contained in:
@@ -664,6 +664,28 @@ func (s *Redis) GetDelCtx(ctx context.Context, key string) (string, error) {
|
||||
return val, err
|
||||
}
|
||||
|
||||
// GetEx is the implementation of redis getex command.
|
||||
// Available since: redis version 6.2.0
|
||||
func (s *Redis) GetEx(key string, seconds int) (string, error) {
|
||||
return s.GetExCtx(context.Background(), key, seconds)
|
||||
}
|
||||
|
||||
// GetExCtx is the implementation of redis getex command.
|
||||
// Available since: redis version 6.2.0
|
||||
func (s *Redis) GetExCtx(ctx context.Context, key string, seconds int) (string, error) {
|
||||
conn, err := getRedis(s)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
val, err := conn.GetEx(ctx, key, time.Duration(seconds)*time.Second).Result()
|
||||
if errors.Is(err, red.Nil) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
return val, err
|
||||
}
|
||||
|
||||
// GetSet is the implementation of redis getset command.
|
||||
func (s *Redis) GetSet(key, value string) (string, error) {
|
||||
return s.GetSetCtx(context.Background(), key, value)
|
||||
|
||||
@@ -1104,6 +1104,45 @@ func TestRedis_GetDel(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestRedis_GetEx(t *testing.T) {
|
||||
t.Run("get_ex", func(t *testing.T) {
|
||||
runOnRedis(t, func(client *Redis) {
|
||||
val, err := client.GetEx("getex_key", 10)
|
||||
assert.Equal(t, "", val)
|
||||
assert.Nil(t, err)
|
||||
|
||||
err = client.Set("getex_key", "getex_value")
|
||||
assert.Nil(t, err)
|
||||
|
||||
val, err = client.GetEx("getex_key", 10)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, "getex_value", val)
|
||||
val, err = client.Get("getex_key")
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, "getex_value", val)
|
||||
|
||||
ttl, err := client.Ttl("getex_key")
|
||||
assert.Nil(t, err)
|
||||
assert.True(t, ttl > 0 && ttl <= 10)
|
||||
|
||||
val, err = client.GetEx("getex_key", 5)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, "getex_value", val)
|
||||
|
||||
ttl, err = client.Ttl("getex_key")
|
||||
assert.Nil(t, err)
|
||||
assert.True(t, ttl > 0 && ttl <= 5)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("get_ex_with_error", func(t *testing.T) {
|
||||
runOnRedisWithError(t, func(client *Redis) {
|
||||
_, err := newRedis(client.Addr, badType()).GetEx("hello", 10)
|
||||
assert.Error(t, err)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
func TestRedis_GetSet(t *testing.T) {
|
||||
t.Run("set_get", func(t *testing.T) {
|
||||
runOnRedis(t, func(client *Redis) {
|
||||
|
||||
Reference in New Issue
Block a user