起因
在某次开发中,发现 golang 使用 redis setnx 总是不是 set 成功,点开 redis 发现超时时间过长。
结论
经过排查发现,是设置 redis setnx 的超时时间出现错误
原因
golang 中 time.Duration 是 int64 的别名,所以直接使用 int64(time.Duration) 是不会出现编译报错的
// A Duration represents the elapsed time between two instants
// as an int64 nanosecond count. The representation limits the
// largest representable duration to approximately 290 years.
type Duration int64
但是,time.Duration的单位是Nanoseconds,如果单位不对千万不要直接转化,而是使用duration提供的方法
// A Time represents an instant in time with nanosecond precision.
func (d Duration) Nanoseconds() int64 { return int64(d) }
func (d Duration) Microseconds() int64 { return int64(d) / 1e3 }
func (d Duration) Milliseconds() int64 { return int64(d) / 1e6 }
func (d Duration) Seconds() float64
func (d Duration) Minutes() float64
func (d Duration) Hours() float64
总结
由于golang存在类型别名,可以进行无损转化,但是直接转换会导致本来应有的校验或者逻辑被忽略。所以最好不要直接转化。