我正在使用拦截器来验证用户,我希望使用Redis可以缓存。下面是代码。缓存在拦截器内部不起作用。 @Cacheable
在我的控制器中工作我测试了
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import uk.co.rullion.ledger.exception.UnauthorisedAccessException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
@Component
@Profile({"dev","prod"})
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object object) throws UnauthorisedAccessException {
Map<String,List> userRoles = authenticateUser(username, password);
....
return authorizationResult;
}
@Cacheable(value="authenticateUser")
public Map<String,List> authenticateUser(String username, String password) {
//authenticating user logic
// there service layer call is happening everytime
return userRoles;
}
}
答案 0 :(得分:0)
只有通过代理进入的外部方法调用才有 截获。这意味着自我调用实际上是一种方法 在目标对象内调用目标对象的另一个方法, 即使在运行时也不会导致实际的缓存拦截 调用的方法用@Cacheable标记。
将authenticateUser方法调用解压缩到一个单独的服务中,并将该类声明为@Service / @Component,并使用@cacheable注释缓存单个方法