golang 中的定时器(timer),更巧妙的处理timeout
今天看到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的更多相关文章
- python中实现定时器Timer
实现定时器最简单的办法是就是循环中间嵌time.sleep(seconds), 这里我就不赘述了 # encoding: UTF-8 import threading #Timer(定时器)是Thre ...
- Python--day41--threading中的定时器Timer
定时器Timer:定时开启线程 代码示例: #定时开启线程 import time from threading import Timer def func(): print('时间同步') #1-3 ...
- [ Javascript ] JavaScript中的定时器(Timer) 是怎样工作的!
作为入门者来说.了解JavaScript中timer的工作方式是非常重要的.通常它们的表现行为并非那么地直观,而这是由于它们都处在一个单一线程中.让我们先来看一看三个用来创建以及操作timer的函数. ...
- golang中的定时器
1. timer 定时器,时间到了执行,只执行一次 package main import ( "fmt" "time" ) func main() { // ...
- Java中的定时器Timer
java.util.Timer是一个实用工具类,该类用来调度一个线程,使线程可以在将来某一时刻开始执行. Java的Timer类可以调度一个线程运行一次,或定期运行. java.util.TimerT ...
- 线程中的定时器Timer类
Timer 定时器 几分钟之后执行一个任务. 创建了一个定时器相当于开启了一条线程,TimerTask相当于一个线程的任务.内部使用wait/notify机制来实现的. 用法非常的简单 就足以里面的 ...
- Swoole 中毫秒定时器(Timer)的使用
间隔定时器, tick 定时器会持续触发,直到调用 clear() 清除为止. $timer = Swoole\Timer::tick(3000, function (int $timer_id, $ ...
- 解决windows 服务中定时器timer 定时偶尔失效 问题
最近做个windows 服务,功能是:定时执行一个任务:自动登录到一个网站后,点击相关网面上的按钮button. 在处理的过程中发现定时器老是不定时的失效,失效时间没有规律. 由于刚开始处于测试阶段, ...
- Java中定时器Timer致命缺点(附学习方法)
简介 这篇文章我一直在纠结到底要不要写,不想写一来因为定时器用法比较简单,二来是面试中也不常问.后来还是决定写了主要是想把自己分析问题思路分享给大家,让大家在学习过程中能够参考,学习态度我相信大部分人 ...
随机推荐
- HTML5 + AJAX ( jQuery版本 ) 文件上传带进度条
页面技术:HTML5 + AJAX ( jQuery) 后台技术:Servlet 3.0 服务器:Tomcat 7.0 jQuery版本:1.9.1 Servlet 3.0 代码 package or ...
- gt811 driver
#include <linux/module.h> #include <linux/i2c.h> #include <linux/platform_device.h> ...
- 使用js事件机制进行通用操作&特定业务处理的协调
背景:提供一个通用的功能工具条,工具条会在特定的事件响应时进行一些通用处理:第三方系统使用iframe嵌入这个工具条中,在工具条的特定的事件响应时进行通用处理的时候,有可能第三方系统会有一些自己的业务 ...
- jquery库实现iframe自适应内容高度和宽度
javascript原生和jquery库实现iframe自适应内容高度和宽度---推荐使用jQuery的代码! <iframe src="index.php" id=&qu ...
- 5.3 SpEL语法
SqEL是一个可以独立于spring的表达式语言,即它可以用在XML中对语法进行简化 5.3 SpEL语法5.3.1 基本表达式一.字面量表达式: SpEL支持的字面量包括:字符串.数字类型(int. ...
- 关于Java中的HashMap的深浅拷贝的测试与几点思考
0.前言 工作忙起来后,许久不看算法,竟然DFA敏感词算法都要看好一阵才能理解...真是和三阶魔方还原手法一样,田园将芜,非常可惜啊. 在DFA算法中,第一步是需要理解它的数据结构,在此基础上,涉及到 ...
- (转)c++ new/delete,new[]/delete[]原理解析
转自: 推荐:http://www.cnblogs.com/hazir/p/new_and_delete.html http://blog.csdn.net/crazyboyzzx/article/d ...
- 【mysql】windows7 安装 Mysql
From: http://jingyan.baidu.com/article/e52e3615a1128c40c70c5174.html 安装(解压) ZIP Archive版是免安装的.只要解压就行 ...
- CSS顶级技巧大放送,div+css布局必知
字体大小使用px 在一行内声明CSS 对比下面两个: h2 {font-size:18px; border:1px solid blue; color:#000; } h2 { font-siz ...
- 【转】C++ Incorrect Memory Usage and Corrupted Memory(模拟C++程序内存使用崩溃问题)
http://www.bogotobogo.com/cplusplus/CppCrashDebuggingMemoryLeak.php Incorrect Memory Usage and Corru ...