如果从doFilter调用,则Spring Cache无法正常工作。
请注意,如果未从doFilter()调用,则Spring缓存正在工作(例如,如果从休息服务调用)
如何在doFilter()中启用缓存? (也许在doFilter中不允许缓存?)
@Configuration
@EnableCaching
public class CredentialsInjectionFilter implements javax.servlet.Filter {
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(Arrays.asList(
new ConcurrentMapCache("tenants")
));
return cacheManager;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
display(5);
filterChain.doFilter(servletRequest, servletResponse);
}
@Cacheable("tenants")
public void display(int number) {
// if cache working properly, code below will not execute after the first calling
for(int i=0; i<50; i++) {
System.out.println("ramon called" +number);
}
}
答案 0 :(得分:0)
如何扩展org.springframework.web.filter.GenericFilterBean,并将缓存详细信息移动到单独的服务类中
<强> CacheService 强>
import java.util.Arrays;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class CacheService{
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(Arrays.asList(
new ConcurrentMapCache("tenants")
));
return cacheManager;
}
@Cacheable("tenants")
public void display(int number) {
// if cache working properly, code below will not execute after the first calling
for(int i=0; i<50; i++) {
System.out.println("ramon called" +number);
}
}
}
<强> CredentialsInjectionFilter 强>
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.GenericFilterBean;
@Component
public class CredentialsInjectionFilter extends GenericFilterBean {
@Autowired
private CacheService cacheService;
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
cacheService.display(5);
filterChain.doFilter(servletRequest, servletResponse);
}
}