Skip to content

Commit

Permalink
预留了 config,支持在 token 失效之前进行自动刷新
Browse files Browse the repository at this point in the history
  • Loading branch information
SALTWOOD committed Mar 2, 2024
1 parent 4ad0eed commit d8e1b3b
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
19 changes: 19 additions & 0 deletions CSharp-OpenBMCLAPI/Modules/Config.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpOpenBMCLAPI.Modules
{
public class Config
{
// 指示 token 应当在距离其失效前的多少毫秒进行刷新
public int refreshTokenTime;

public Config()
{
this.refreshTokenTime = 1800000;
}
}
}
13 changes: 13 additions & 0 deletions CSharp-OpenBMCLAPI/Modules/SharedData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpOpenBMCLAPI.Modules
{
public static class SharedData
{
public static Config Config { get; set; } = new Config();
}
}
24 changes: 23 additions & 1 deletion CSharp-OpenBMCLAPI/Modules/TokenManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ namespace CSharpOpenBMCLAPI.Modules
internal class TokenManager
{
private readonly string CLUSTER_ID, CLUSTER_SECRET;
private Task? _updateTask;

private Token token;
private object _writeLocker = new object();

public Token Token { get { lock (_writeLocker) return token; } }

public TokenManager(ClusterInfo info)
{
Expand Down Expand Up @@ -44,9 +50,25 @@ public async Task<Token> FetchToken()

resp = await client.PostAsync($"openbmclapi-agent/token", httpContent);
string tokenJson = await resp.Content.ReadAsStringAsync();
Token token = JsonConvert.DeserializeObject<Token>(tokenJson);

// 锁定 token,以免其他线程同时进行读取出现问题
lock (this._writeLocker)
{
this.token = JsonConvert.DeserializeObject<Token>(tokenJson).ThrowIfNull();

this._updateTask = Task.Run(() =>
{
Thread.Sleep(this.token.ttl - SharedData.Config.refreshTokenTime);
RefreshToken();
});
}

return token;
}

public void RefreshToken()
{
FetchToken().Wait();
}
}
}

0 comments on commit d8e1b3b

Please sign in to comment.