[英]Spring Cache not working in doFilter
如果從doFilter調用,Spring Cache不起作用。
請注意,如果未從doFilter()調用,則Spring緩存將正常工作(例如,如果從rest服務調用)
如何在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);
}
}
如何擴展org.springframework.web.filter.GenericFilterBean並將緩存詳細信息移到單獨的服務類中
緩存服務
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.