View and Data API tips: 快取Access Token

峻祁連發表於2015-02-25

對於雲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中。

相關文章