我想制作一个应该包含访问 token 的 Token
类。但是,一旦 token 在下次使用时过期,则应刷新 token 。问题是这需要以线程安全的方式处理。只要 isExpired
为假,每个人都应该能够访问 token 。但是一旦 token 过期,只应进行一次更新 token 的调用,而其他试图读取 token 的调用则必须等待。
到目前为止,我有以下内容:
public class Token {
private boolean isExpired = true;
private String token = "";
private final AccessTokenClient tokenRetriever;
public Token(AccessTokenClient tokenRetriever) {
this.tokenRetriever = tokenRetriever;
}
public String getToken() {
// If isExpired true
// Use tokenRetriever to get a new token
// Only one request to getToken should try to update the token, others trying to call getToken has to wait.
return null;
}
}
我的问题是:在 Java 8 中实现这样的访问 token 缓存的惯用方法是什么?
最佳答案
这是我能想到的最基本的例子:
public class Token {
private final AccessTokenClient tokenRetriever;
private final Object monitor;
private volatile boolean isExpired = true;
private volatile String token = "";
public Token(AccessTokenClient tokenRetriever) {
this.tokenRetriever = tokenRetriever;
this.monitor = new Object();
}
public String getToken() {
if (this.isExpired) {
synchronized (this.monitor) {
// intended double check!
if (this.isExpired) {
this.token = this.tokenRetriever.retrieveToken();
this.isExpired = false;
}
}
}
return this.token;
}
}
关于java - 用于在 Java 中保存访问 token 的线程安全类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56495189/