今天看到kite项目中的一段代码,发现挺有意思的。

// generateToken returns a JWT token string. Please see the URL for details:
// http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-13#section-4.1
func generateToken(aud, username, issuer, privateKey string) (string, error) {
tokenCacheMu.Lock()
defer tokenCacheMu.Unlock() uniqKey := aud + username + issuer // neglect privateKey, its always the same
signed, ok := tokenCache[uniqKey]
if ok {
return signed, nil
} tknID, err := uuid.NewV4()
if err != nil {
return "", errors.New("Server error: Cannot generate a token")
} // Identifies the expiration time after which the JWT MUST NOT be accepted
// for processing.
ttl := TokenTTL // Implementers MAY provide for some small leeway, usually no more than
// a few minutes, to account for clock skew.
leeway := TokenLeeway tkn := jwt.New(jwt.GetSigningMethod("RS256"))
tkn.Claims["iss"] = issuer // Issuer
tkn.Claims["sub"] = username // Subject
tkn.Claims["aud"] = aud // Audience
tkn.Claims["exp"] = time.Now().UTC().Add(ttl).Add(leeway).Unix() // Expiration Time
tkn.Claims["nbf"] = time.Now().UTC().Add(-leeway).Unix() // Not Before
tkn.Claims["iat"] = time.Now().UTC().Unix() // Issued At
tkn.Claims["jti"] = tknID.String() // JWT ID signed, err = tkn.SignedString([]byte(privateKey))
if err != nil {
return "", errors.New("Server error: Cannot generate a token")
} // cache our token
tokenCache[uniqKey] = signed // cache invalidation, because we cache the token in tokenCache we need to
// invalidate it expiration time. This was handled usually within JWT, but
// now we have to do it manually for our own cache.
time.AfterFunc(TokenTTL-TokenLeeway, func() {
tokenCacheMu.Lock()
defer tokenCacheMu.Unlock() delete(tokenCache, uniqKey)
})
return signed, nil
}

这里的  time.AfterFunc 来做token的timeout处理,是我之前都不知道的。

我之前的做法,自己启动一个 单独的 goroutine,对所有的token做遍历,判断是否timeout,timout了就进行删除操作。

看到了这段代码,第一个感觉是很妙,第二个是如果用起来,会不会有啥副作用。

翻看源码:https://golang.org/src/time/sleep.go?h=AfterFunc#L116

// AfterFunc waits for the duration to elapse and then calls f
// in its own goroutine. It returns a Timer that can
// be used to cancel the call using its Stop method.
func AfterFunc(d Duration, f func()) *Timer {
t := &Timer{
r: runtimeTimer{
when: when(d),
f: goFunc,
arg: f,
},
}
startTimer(&t.r)
return t
}

这里的startTimer 是用了系统自身的timer实现,只不过是golang在这里做了一层兼容各个平台的封装,应该是没有什么副作用啦。

    // Interface to timers implemented in package runtime.
// Must be in sync with ../runtime/runtime.h:/^struct.Timer$
type runtimeTimer struct {
i int
when int64
period int64
f func(interface{}, uintptr) // NOTE: must not be closure
arg interface{}
seq uintptr
} // when is a helper function for setting the 'when' field of a runtimeTimer.
// It returns what the time will be, in nanoseconds, Duration d in the future.
// If d is negative, it is ignored. If the returned value would be less than
// zero because of an overflow, MaxInt64 is returned.
func when(d Duration) int64 {
if d <= {
return runtimeNano()
}
t := runtimeNano() + int64(d)
if t < {
t = << - // math.MaxInt64
}
return t
} 40 func startTimer(*runtimeTimer)
41 func stopTimer(*runtimeTimer) bool

不得不感慨,原生库还是有很多好东东的,需要自己慢慢发觉。

golang 中的定时器(timer),更巧妙的处理timeout的更多相关文章

  1. python中实现定时器Timer

    实现定时器最简单的办法是就是循环中间嵌time.sleep(seconds), 这里我就不赘述了 # encoding: UTF-8 import threading #Timer(定时器)是Thre ...

  2. Python--day41--threading中的定时器Timer

    定时器Timer:定时开启线程 代码示例: #定时开启线程 import time from threading import Timer def func(): print('时间同步') #1-3 ...

  3. [ Javascript ] JavaScript中的定时器(Timer) 是怎样工作的!

    作为入门者来说.了解JavaScript中timer的工作方式是非常重要的.通常它们的表现行为并非那么地直观,而这是由于它们都处在一个单一线程中.让我们先来看一看三个用来创建以及操作timer的函数. ...

  4. golang中的定时器

    1.  timer 定时器,时间到了执行,只执行一次 package main import ( "fmt" "time" ) func main() { // ...

  5. Java中的定时器Timer

    java.util.Timer是一个实用工具类,该类用来调度一个线程,使线程可以在将来某一时刻开始执行. Java的Timer类可以调度一个线程运行一次,或定期运行. java.util.TimerT ...

  6. 线程中的定时器Timer类

    Timer 定时器 几分钟之后执行一个任务. 创建了一个定时器相当于开启了一条线程,TimerTask相当于一个线程的任务.内部使用wait/notify机制来实现的. 用法非常的简单  就足以里面的 ...

  7. Swoole 中毫秒定时器(Timer)的使用

    间隔定时器, tick 定时器会持续触发,直到调用 clear() 清除为止. $timer = Swoole\Timer::tick(3000, function (int $timer_id, $ ...

  8. 解决windows 服务中定时器timer 定时偶尔失效 问题

    最近做个windows 服务,功能是:定时执行一个任务:自动登录到一个网站后,点击相关网面上的按钮button. 在处理的过程中发现定时器老是不定时的失效,失效时间没有规律. 由于刚开始处于测试阶段, ...

  9. Java中定时器Timer致命缺点(附学习方法)

    简介 这篇文章我一直在纠结到底要不要写,不想写一来因为定时器用法比较简单,二来是面试中也不常问.后来还是决定写了主要是想把自己分析问题思路分享给大家,让大家在学习过程中能够参考,学习态度我相信大部分人 ...

随机推荐

  1. php html 转义

    html_entity_decode($string);htmlentities($string);htmlspecialchars($string);htmlspecialchars_decode( ...

  2. oracle中select clob的返回类型

    当select的字段是clob类型的数据时,但是数据长度在2000字节到4000字节时,默认转为long类型. 所以当用insert into select的时候,预期插入的是clob类型,但是报or ...

  3. ajax——用ajax写用户注册

    zhuce.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://w ...

  4. 使用js事件机制进行通用操作&特定业务处理的协调

    背景:提供一个通用的功能工具条,工具条会在特定的事件响应时进行一些通用处理:第三方系统使用iframe嵌入这个工具条中,在工具条的特定的事件响应时进行通用处理的时候,有可能第三方系统会有一些自己的业务 ...

  5. 集中精力的重要性(The Importance of Focus)

    集中精力的重要性(The Importance of Focus) 在当今激烈竞争的经济中,你需要集中精力使得你公司的独特方面精益求精.并且你需要每天将精力集中在改进你的公司上.通过终极外包,单干型企 ...

  6. jQuery补充,模拟图片放大镜

    jQuery补充,模拟图片放大镜 html <!DOCTYPE html> <html lang="en"> <head> <meta c ...

  7. poj 3348:Cows(计算几何,求凸包面积)

    Cows Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 6199   Accepted: 2822 Description ...

  8. Juicer——a fast template engine

    https://blog.csdn.net/yutao_struggle/article/details/79201688 当前最新版本: 0.6.8-stable Juicer 是一个高效.轻量的前 ...

  9. 编程之美 set 14 小飞的电梯调度算法

    题目 电梯每次上升只停一次, 求问电梯停在哪一楼能够保证乘坐电梯的所有乘客爬楼层的层数之和最小 思路 假设电梯的层数是 m, 乘客人数是 n 1. 枚举, 时间复杂度是 o(mn) 2. 滚动解法. ...

  10. 剑指 offer set 23 n 个骰子的点数

    题目 把 n 个骰子扔到地上, 所有骰子朝上一面的点数之和为 s. 输入 n, 打印出 s 所有可能的值出现的概率. 思路 1. 基于递归的求解方法. 深度为 n 的 dfs, 相当于求全排列, 时间 ...