我有一個使用 Retrofit 向安全服務器發出請求的 Spring Boot 應用程式。
我的端點:
public interface ServiceAPI {
@GET("/v1/isrcResource/{isrc}/summary")
Call<ResourceSummary> getResourceSummaryByIsrc(@Path("isrc") String isrc);
}
public interface TokenServiceAPI {
@FormUrlEncoded
@POST("/bbcb6b2f-8c7c-4e24-86e4-6c36fed00b78/oauth2/v2.0/token")
Call<Token> obtainToken(@Field("client_id") String clientId,
@Field("scope") String scope,
@Field("client_secret") String clientSecret,
@Field("grant_type") String grantType);
}
配置類:
@Bean
Retrofit tokenAPIFactory(@Value("${some.token.url}") String tokenUrl) {
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(tokenUrl)
.addConverterFactory(JacksonConverterFactory.create());
return builder.build();
}
@Bean
Retrofit serviceAPIFactory(@Value("${some.service.url}") String serviceUrl, TokenServiceAPI tokenAPI) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new ServiceInterceptor(clientId, scope, clientSecret, grantType, apiKey, tokenAPI))
.build();
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(repertoireUrl)
.client(okHttpClient)
.addConverterFactory(JacksonConverterFactory.create());
return builder.build();
}
攔截器將授權標頭添加到每個請求
public class ServiceInterceptor implements Interceptor {
public ServiceInterceptor(String clientId,
String scope,
String clientSecret,
String grantType,
String apiKey,
TokenServiceAPI tokenAPI) {
this.clientId = clientId;
this.scope = scope;
this.clientSecret = clientSecret;
this.grantType = grantType;
this.apiKey = apiKey;
this.tokenAPI = tokenAPI;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader(AUTHORIZATION_HEADER, getToken())
.addHeader(API_KEY_HEADER, this.apiKey)
.build();
return chain.proceed(newRequest);
}
private String getToken() throws IOException {
retrofit2.Response<Token> tokenResponse = repertoireTokenAPI.obtainToken(clientId, scope, clientSecret, grantType).execute();
String accessToken = "Bearer " tokenAPI.body().getAccessToken();
return accessToken;
}
}
這按預期作業,問題是每個請求都請求令牌,而不是使用現有的有效令牌。如何將令牌存盤在某處并重新使用它?我想知道 Retrofit 是否有內置的解決方案。
uj5u.com熱心網友回復:
快取的可能選項:
添加咖啡因
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
添加@Cacheable("your-token-cache-name")回傳令牌的方法,getToken如上所示
在下面的配置中添加最大快取大小和過期配置,application.yml
例如 500 個條目和 10 分鐘
spring.cache.cache-names=your-token-cache-name
spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s
示例來自:https ://www.javadevjournal.com/spring-boot/spring-boot-with-caffeine-cache/
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/412172.html
標籤:
