为什么这个缓存没有被驱逐?

时间:2016-10-11 20:20:09

标签: java spring caching

AdminSOAPRunner:

@Component
public class AdminSOAPRunner {

    private static final Logger LOGGER = LoggerFactory.getLogger(AdminSOAPRunner.class);

    private String userId;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    @Autowired
    private AdminAuth adminAuthenticator;

    @Autowired
    private AdminBean adminBean;

    private AccountService accountService;


    private void setBindingProviderByAccountService() {
        WSBindingProvider bindingProvider = (WSBindingProvider) this.accountService;
        bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, adminBean.getAccountUrl());
        LOGGER.info("Endpoint {}", adminBean.getAccountUrl());
    }

    private RequestInfo getRequestInfo() {

        RequestInfo requestInfo = new RequestInfo();

        requestInfo.setAppName(adminBean.getAppName());
        requestInfo.setUserId(this.getUserId());
        requestInfo.setTrace(UUID.randomUUID().toString());
        return requestInfo;

    }

    public List<ApplyAccountResult> getAccounts(ApplyAccountRequest request) {
        AccountService_Service service = null;

        URL serviceWSDL = AccountService_Service.class.getResource("/Account-service/Account-service.wsdl");
        service = new AccountService_Service(serviceWSDL);

        SOAPHandlerResolver SOAPHandlerResolver = new SOAPHandlerResolver();
        SOAPHandlerResolver.getHandlerList().add(new SOAPHandler(this.adminAuthenticator));
        service.setHandlerResolver(SOAPHandlerResolver);

        if (accountService == null) {
            accountService = service.getAccountService();
        }

        setBindingProviderByAccountService();

        ApplyAccountAccountResponse response = null;
        LOGGER.info("Making a SOAP request.");
        response = AccountService.applyAccount(request, getRequestInfo(), new Holder<ResponseInfo>());
        LOGGER.info("SOAP request completed.");
        return response.getApplyAccountResults();
    }

SOAPHandlerResolver:

public class SOAPHandlerResolver implements HandlerResolver {

    @SuppressWarnings("rawtypes")
    private List<Handler> handlerList;

    public SOAPHandlerResolver() {
        this.handlerList = null;
    }

    @SuppressWarnings("rawtypes")
    public List<Handler> getHandlerList() {
        if (this.handlerList == null) {
            this.handlerList = new ArrayList<>();
        }
        return this.handlerList;
    }

    @SuppressWarnings("rawtypes")
    @Override
    public List<Handler> getHandlerChain(PortInfo portInfo) {
        List<Handler> handlerChain = new ArrayList<>();
        if (this.handlerList == null || this.handlerList.isEmpty()) {
            this.handlerList = new ArrayList<>();
            this.handlerList.add(new SOAPHandler(null));
        }
        handlerChain.addAll(this.handlerList);
        return handlerChain;
    }
}

SOAPHandler

public class SOAPHandler implements SOAPHandler<SOAPMessageContext> {

    private AdminAuth adminAuth;
    private static final Logger LOGGER = LoggerFactory.getLogger(SOAPHandler.class);

    public MosaicOnboardSOAPHandler(AdminAuth adminAuth) {
        if (adminAuth == null) {
            adminAuth = new AdminAuth();
            LOGGER.info("AdminAuth found null. Creating new adminAuth instance.");
        }
        this.adminAuth = adminAuth;
    }

    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (outboundProperty) {
            @SuppressWarnings("unchecked")
            Map<String, List<String>> headers = (Map<String, List<String>>) context.get(MessageContext.HTTP_REQUEST_HEADERS);
            if (headers == null) {
                headers = new HashMap<>();
                context.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
            }
            List<String> cookie = headers.get("Cookie");
            if (cookie == null) {
                cookie = new ArrayList<>();
                headers.put("Cookie", cookie);
            }
            cookie.add(this.adminAuth.getToken());
        }
        return true;
    }

    @Override
    public boolean handleFault(SOAPMessageContext context) {
        return false;
    }

    @Override
    public void close(MessageContext context) {

    }

    @Override
    public Set<QName> getHeaders() {
        return null;
    }
}

AdminAuth:

@Component
public class AdminAuth {

    @Autowired
    private AdminBean adminBean;

    private static final Logger LOG = LoggerFactory.getLogger(Admin.class);
    private String token;

    private void generateToken() {

        try {
            AdminTokenHelper adminTokenHelper = new AdminTokenHelper(adminBean.getAutheticationServerURL(), adminBean.getLicense());


            token = adminTokenHelper.getToken(adminBean.getUsername(), adminBean.getPassword().toCharArray());

            LOG.info("Token generation successful");
        } catch (Exception ex) {
            ex.printStackTrace();
            LOG.error("Token generation failed");
            LOG.error(ex.getMessage());
            throw new RuntimeException("Token generation failed", ex);
        }
    }

    @Cacheable(value = "tokenCache")
    public String getToken() {
        LOG.warn("Token not available. Generating a new token.");
        generateToken();
        return token;
    }
}

ehcache.xml中

 <cache name="tokenCache" maxEntriesLocalHeap="1" eternal="false" timeToIdleSeconds="895" timeToLiveSeconds="895" memoryStoreEvictionPolicy="LRU"/>

的applcation

@EnableCaching
@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    public static void main(final String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
        return application.sources(Application.class).profiles(determineEnvironmentProfile());
    }
}

在AdminAuth中,它使用功能用户生成令牌。为身份验证生成的令牌将在15分钟后到期。所以我的目的是编写缓存,以便ui的所有调用都可以使用相同的令牌而不管实际用户。所以我将时间设置为14:55以生成新令牌。现在问题发生在15分钟之后,缓存不会驱逐旧的toeken,因此调用使用旧的和过期的令牌而失败。 我尝试了不同的驱逐政策,如LRU,LFU,FiFO,但没有任何工作。这些调用来自ui通过tomcat容器在spring boot 1.3。

为什么这不会被驱逐?我错过了什么?任何帮助表示赞赏

2 个答案:

答案 0 :(得分:0)

@Cacheable(value = "tokenCache")替换为@Cacheable("tokenCache")

答案 1 :(得分:0)

来自评论:

缺少对spring-boot-starter-cache的依赖。这阻止了Spring Boot自动配置CacheManager。一旦添加了此依赖项,缓存配置就会起作用。

请参阅http://docs.spring.io/spring-boot/docs/1.3.x/reference/html/boot-features-caching.html