12306的架构当然不止这么一点,仅对其中的限流做出讨论
、
2306购票 zhj优化版
限制每台服务器访问后层的次数
每台服务器都设置一个buffer值 每次调用接口,首先从缓存中取出buffer,将buffer减1,更新缓存,然后从返回值中取出剩余值 通过一定算法确定buffer,更新缓存,后续请求只有当buffer大于0时才会调用方法
等于0后直接拦截接口,缓存要设置有效时长,防止有人退票
这里有个问题 首次更新redis时需要用redis的 lua脚本
local current = redis.call('GET', KEYS[1])
if current == ARGV[2]
then redis.call('SET', KEYS[1], ARGV[1])
return ARGV[1]
end
return current
JAVA执行代码
final List<String> keys = Collections.singletonList(key);
final List<String> args = Collections.singletonList(requestId);
redisTemplate.execute(new RedisCallback<Long>() {
@Override
public Long doInRedis(RedisConnection connection) throws DataAccessException {
Object commands = connection.getNativeConnection();
//fixed EvalSha is not supported in cluster environment.
long status = 0L;
status = (Long) ((JedisCluster) commands).eval("lua脚本", keys, args);
return status;
}
});
实现流程:
(1)获取KEYS[1]的值
(2)比较传入的期望值和redis的真实值
(3)如果两值相等,将新值放入redis中,返回新值
(4)如果两值不等,将redis中的旧值返回
(5)程序判读返回值,确定是否修改成功,不成功,则继续尝试修改redis