View and Data API tips: 缓存Access Token

对于云API服务,常见的方式就是按照API调用次数收费,某些API调用也就有某些限制,比如在特定时间内只允许调用指定的次数以免造成滥用。虽然Autodesk的view and Data API目前还没有应用这样的限制,但我们最好也能实现这样的机制,比如对于或者Access Token这样的操作,一个Access Token是有一定的有效期的,在这个token的有效期内,我们就没必要重复发出API调用获取新的Acces Token,只有返回仍然有效的token就可以了。下面是c#实现的简单的逻辑,用一个全局静态变量来缓存Access Token:

public class Util
{
    private static readonly ILog logger = LogManager.GetLogger(typeof(Util));

    string baseUrl = "";
    RestClient m_client;


    public static AccessToken token;
    public static DateTime issueDateTime;
    //refresh token if the token is about to expire in 5 seconds
    public static int ABOUT_EXPIRED_SECONDS = 5;


    public Util(string baseUrl)
    {
        this.baseUrl = baseUrl;
        m_client = new RestClient(baseUrl);
    }

    public AccessToken GetAccessToken(string clientId, string clientSecret)
    {
        //no token or token is going to be expired
        // (less than ABOUT_EXPIRED_SECONDS)

        if (token == null
            || (DateTime.Now - issueDateTime).TotalSeconds
                > (token.expires_in - ABOUT_EXPIRED_SECONDS))
        {
            RestRequest req = new RestRequest();
            req.Resource = "authentication/v1/authenticate";
            req.Method = Method.POST;
            req.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            req.AddParameter("client_id", clientId);
            req.AddParameter("client_secret", clientSecret);
            req.AddParameter("grant_type", "client_credentials");
            //avoid CORS issue, do not use this if you just need to get access token from same domain

            req.AddHeader("Access-Control-Allow-Origin", "*");

            IRestResponse<AccessToken> resp = m_client.Execute<AccessToken>(req);
            logger.Debug(resp.Content);

            if (resp.StatusCode == System.Net.HttpStatusCode.OK)
            {
                AccessToken ar = resp.Data;
                if (ar != null)
                {
                    token = ar;

                    //update the token issue time
                    issueDateTime = DateTime.Now;


                }
            }
            else
            {

                logger.Fatal("Authentication failed! clientId:" + clientId);

            }

        }
        else
        {
            ;//Do nothing, use the saved access token in static var
        }

        return token;
    }


    }

 

当然,根据需要你可以选择其他的方式,比如把token保存在数据库中,或者memcache中。


Related Posts Plugin for WordPress, Blogger...