Spring Boot缓存不起作用

时间:2014-12-13 11:11:50

标签: spring spring-boot spring-cache

我尝试配置spring缓存,但该方法仍然执行。我有以下代码,CivilStatus缓存无法正常工作。方法getCivilStatus()始终执行。有人知道原因吗?

@Configuration
@EnableCaching
public class ApplicationConfig {

@Autowired
private SocioDemographicInfoService socioDemographicInfo;


@Bean
public CacheManager cacheManager() {
    SimpleCacheManager cacheManager = new SimpleCacheManager();
    cacheManager.setCaches(Arrays.asList(           
            new ConcurrentMapCache("civilStatus");

    return cacheManager;
}
}   



@Service
public class SocioDemographicInfoService {



@Cacheable(value="civilStatus")
public Map<String, String> getCivilStatus(){
    log.info("Retrieving civilStatus");
    Map<String, String> civilStatus = new HashMap<String, String>();
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";
    try {
        ClassLoader classLoader = getClass().getClassLoader();
        File file = new File(classLoader.getResource("CatalogoEstadoCivil.csv").getFile());
        br = new BufferedReader(new FileReader(file));
        while ((line = br.readLine()) != null) {
            String[] cod = line.split(cvsSplitBy);
            civilStatus.put(cod[0].trim(), cod[1]);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return civilStatus;
}
}

}

2 个答案:

答案 0 :(得分:1)

我相信你正在使用spring boot并使用类似这样的类设置服务器(如下所示)。在同一个类上添加EnableCaching批注并定义下面给出的CacheManager,而不是单独的配置类。这将确保在您的类初始化之前启用缓存。

@Configuration
@EnableAutoConfiguration
@ComponentScan
@EnableCaching
@PropertySource(ignoreResourceNotFound = true, value = {"classpath:application.properties"})
@ImportResource(value = { "classpath*:spring/*.xml" })
public class MyBootServer{

public static void main(String args[]){
    ApplicationContext ctx = SpringApplication.run(MyBootServer.class, args);
}

@Bean(name="cacheManager")
public CacheManager getCacheManager() {
...// Your code
}
}

你的所有代码都没有错。我在my spring boot sample code中测试了您的配置并且它可以正常工作

答案 1 :(得分:0)

您不需要AOP和缓存复杂性,您的用例更简单。只需创建一个在启动时加载文件的方法,让getCivilStatus返回该地图。更简单。

@Service
public class SocioDemographicInfoService implements ResourceLoaderAware {

    private final Map<String, String> civilStatus = new HashMap<String, String>();

    private ResourceLoader loader;

    @PostConstruct
    public void init() {
        log.info("Retrieving civilStatus");
        Map<String, String> civilStatus = new HashMap<String, String>();
        BufferedReader br = null;
        String line = "";
        String cvsSplitBy = ",";
        Resource input = loader.getResource("classpath:CatalogoEstadoCivil.csv"));
        if (input.isReadable() ) {
            File file = input.getFile();
            br = new BufferedReader(new FileReader(file));
            try {
                while ((line = br.readLine()) != null) {
                    String[] cod = line.split(cvsSplitBy);
                    civilStatus.put(cod[0].trim(), cod[1]);
                }
            } catch (IOException e) {
                logger.error("Error reading file", e_;
            } finally {
                if (br != null) {
                    try { br.close() } catch( IOException e) {}
                }               
            }   
        }   
    }

    public Map<String, String> getCivilStatus() {
        return this.civilStatus;
    }

    public void setResourceLoader(ResourceLoader loader) {
        this.loader=loader;
    }

}

这样的事情应该有效。它在构造bean之后加载你的(这段代码可能通过使用像commons-io这样的东西来优化)。注意我使用Springs ResourceLoader来加载文件。