春天-使用缓存

时间:2018-10-07 11:57:20

标签: java spring caching

我有一个spring项目,需要在服务类中使用缓存,如下所示:

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

@Service 
public class WebAuthnServer {  
      private final Cache<String, RegistrationRequest> registerRequestStorage = newCache(); 

      private static <K, V> Cache<K, V> newCache() {
        return CacheBuilder.newBuilder()
        .maximumSize(100)
        .expireAfterAccess(10, TimeUnit.MINUTES)
        .build();
      }

      public Either<String, RegistrationRequest> startRegistration(String username, String displayName, String credentialNickname, boolean requireResidentKey) { 
        if (userStorage.getRegistrationsByUsername(username).isEmpty()) { 
             RegistrationRequest request = new RegistrationRequest(...);            
             registerRequestStorage.put(request.getRequestId(), request);
         } else {
             return new Left("The username \"" + username + "\" is already registered.");
         }
      }
 }

我有registerRequestStorage缓存,并使用方法startRegistration将一些数据放入缓存。但是,当我尝试通过另一种方法获取此数据时,缓存为空。

 public Either<List<String>, SuccessfulRegistrationResult> finishRegistration(String responseJson) { 
    RegistrationResponse response = null;
    try {
        response = jsonMapper.readValue(responseJson, RegistrationResponse.class); 
    } catch (IOException e) { 
        return Left.apply(Arrays.asList("Registration failed!", "Failed to decode response object.", e.getMessage()));
    }

    RegistrationRequest request = registerRequestStorage.getIfPresent(response.getRequestId());
    registerRequestStorage.invalidate(response.getRequestId()); 

    if (request == null) {
        logger.info("fail finishRegistration responseJson: {}", responseJson);
        return Left.apply(Arrays.asList("Registration failed!", "No such registration in progress."));
    } else {
        Try<RegistrationResult> registrationTry = rp.finishRegistration(
            request.getPublicKeyCredentialCreationOptions(),
            response.getCredential(),
            Optional.empty()
        );
    }
}

0 个答案:

没有答案