golang限制某一个方法,同一时间只能被执行一次

单点

func f() {
    
    
	rs := atomic.AddInt32(&a, 1)
	defer atomic.AddInt32(&a, -1)
	
	if rs != 1 {
    
    
		return
	}
    
     // handle your job
}

分布式


func TomorrowZero() time.Time {
    
    
	ts := time.Now().AddDate(0, 0, 1).Format("2006-01-02")
	tz, _ := time.ParseInLocation("2006-01-02", ts, time.Local)

	return tz
}
func Once(conn redis.Conn, key string, seconds int) bool {
    
    
	if seconds == -2 {
    
    
		seconds = int(TomorrowZero().Sub(time.Now()).Seconds())
	}

	rs, e := redis.String(conn.Do("set", key, "done", "ex", seconds, "nx"))
	if e == redis.ErrNil {
    
    
		return false
	}
	if rs == "OK" {
    
    
		return true
	}
	return false
}

func main() {
    
    

    if !Once() {
    
    
        return 
    }
   // handle your job
}

猜你喜欢

转载自blog.csdn.net/fwhezfwhez/article/details/114538876