新手问题 环信 @current_token 在 ApplicationController 存活期?请点击进来,标题说不清楚!谢谢啦 大神们

ckl · 2015年01月29日 · 最后由 ruby_sky 回复于 2015年01月29日 · 2704 次阅读

环信 token 有效期一般为七天,第一次获取后判断有效是否再次获取。

# 获取token指令
def get_auth_token_from_remote
  body = {"grant_type" => "client_credentials",
          "client_id" => CLIEND_ID,
          "client_secret" => CLIEND_SECRET}
  result = get_resquest_back("/token","post",false,true,body) get_resquest_back获取tokenhttp的方法
  @current_token = AuthToken.new(result["access_token"],result["expires_in"],result["application"],Time.now)
end
# 获取授权指令
def get_auth_token
  if !defined?(@current_token)
    #都会进入
    get_auth_token_from_remote
  elsif !@current_token.is_valid_token?
    get_auth_token_from_remote
  end
  @current_token
end

问题:不管之前有没有获取过,都会进入 get_auth_token 的第一个判断里,我输出发现是@current_token刷新页面都会变成未定义的。其中 AuthToken 是我自己添加文件写的一个类

class AuthToken

  attr_accessor :access_token, :expires_in, :application,:begin_time
  # 构造方法
  def initialize(access_token, expires_in, application, begin_time)
    @access_token = access_token
    @expires_in = expires_in
    @application = application
    @begin_time = begin_time
  end

  # 判断token是否过期
  def is_valid_token? 
      if !@access_token.empty? && (Time.now - @begin_time) < @expires_in 
      true
    else
      false
    end
  end

end

建议将获取到的 Token 放入到缓存中,然后加入有效期,每次调用的时候首先去缓存取,取不到的时候再请求

#1 楼 @michael0015 谢谢你啊 请问有没有例子参考一下,我之前写的 current_user 有类似,为什么之前是可以存很久呢?

匿名 #3 2015年01月29日

不涉及到所谓“存火期”的问题,你需要弄清楚实例变量@ current_token 的作用域。 我看不清你的具体环境(require 啊,inheritance 啊什么的),也不好判断。不过我感觉你在 attr_accessor 中添加 current_token,应该可以解决这个问题,至于会不会引起新的问题我就不清楚了。

4 楼 已删除

#3 楼 @fuan 在开发模式在缓存配置 config.action_controller.perform_caching = true 是默认 false,我设置 true 啦。attr_accessor :current_token 也是过啦,但是就是每次刷新页面都把他灭啦。我获取 token 写 ApplicationController 中,require 一个 AuthToken 类。谢谢。

#1 楼 @michael0015 #3 楼 @fuan http://hideto.iteye.com/blog/104762/ 其中讲到实例变量的作用域是一次请求,即一次请求结束后@current_user这个实例变量就没了。怎么破?谢谢

把 token 存起来,这个才叫缓存吧?实例变量 只不过是在当前 request 中起到缓存作用(使用了 ||= 符合情况下)。参考:https://github.com/lanrion/weixin_authorize/blob/master/lib/weixin_authorize/adapter/redis_storage.rb

需要 登录 后方可回复, 如果你还没有账号请 注册新账号