2014-11-23 65 views
0

如果從doFilter調用Spring緩存不工作。Spring緩存不工作在doFilter

注意春季緩存工作如果不從的doFilter()調用(例如,如果從靜止服務調用)

我怎樣才能啓用緩存的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); 
     } 
    } 
+1

您正在將@Cacheable應用於不返回任何內容的方法(void返回類型)。你期望在這種情況下會發生什麼? – Jigish 2014-11-23 19:25:18

回答

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); 
    } 
}