Bean未在Mono.map中更新

时间:2018-10-25 11:35:50

标签: java project-reactor reactor

一段时间以来,我一直在尝试调试此问题,但无法完成。我想调用需要访问令牌的服务。因此,在每次调用该服务之前,我都要调用我的IdentityServiceConnector类,该类为我提供访问令牌。

现在,令牌可能会过期。因此,为此,我使用ExpiringMap<k,V>。我为此创建了一个bean,并将其过期:

  @Bean
  public ExpiringMap<String,String> expiringMap() {
    ExpiringMap em = ExpiringMap.builder().expiration(1, TimeUnit.NANOSECONDS).build();  //expire this map after 1 nanosecond
    em.put("accessToken", RandomStringUtils.randomAlphabetic(4));
    return em;
  }

这是我的IdentityConnector.java

@Autowired private ExpiringMap<String, String> expiringMap;

public Mono<IssueToken> getServiceTokenFromIdentity() {

    if (!Objects.isNull(expiringMap.get("accessToken"))) {
      IssueToken issueToken = new IssueToken();
      issueToken.setAccessToken(expiringMap.get("accessToken"));
      return Mono.just(issueToken);
    }

    log.info("Access token expired, Making identity call");

    IssueTokenRequest request =
        IssueTokenRequest.builder()
            .build();

    URI issueTokenUrl =
        UriComponentsBuilder.fromHttpUrl(identityContext.getIssueTokenUrl()).build().toUri();

    long currentTime = System.currentTimeMillis();

    return remoteCall(
            HttpMethod.POST, issueTokenUrl, GsonConvertor.getInstance().serialize(request))
        .map(this::getIssueToken)
        .onErrorMap(
            e -> {
              LogContext logContext =
                  LogContext.builder()
                      .with(
                          LogConstants.Keys.TIMESTAMP,
                          DateUtils.getTransactionTime(System.currentTimeMillis()));
              log.info(
                  Markers.appendEntries(logContext.build()),
                  "Some error occurred while calling identity service ");
              throw new RuntimeException(e.getMessage());
            });
  }

这是getIssueToken()

  private IssueToken getIssueToken(ResponseEntity<String> response) {
    HttpStatus statusCode = response.getStatusCode();
    IssueToken issueToken =
        GsonConvertor.getInstance().deserialize(response.getBody(), IssueToken.class);
    expiringMap.put("accessToken", issueToken.getAccessToken());
    expiringMap.setExpiration(issueToken.getExpiresIn(), TimeUnit.SECONDS);
    return issueToken;
  }

因此,逻辑是每当调用getServiceTokenFromIdentity()时,它都会首先检查ExpiringMap是否过期。对于第一个呼叫,该呼叫将过期,并且将生成初始访问令牌。然后在getIssueToken()中,更新我的ExpiringMap。我面临的问题是,每次调用getServiceTokenFromIdentity()时,都会发现该地图已过期(而不是更新的令牌到期时间为1小时)。

长话短说,我的bean在Mono.map()中没有得到更新。有人可以帮我吗?

0 个答案:

没有答案