字典缓存

一、背景

    项目中,常常把一些常用列表数据设计为字典项,如国家、省、地市、机场、火车站等等,需要在服务启动的时候,即可从数据库(或文件)加载中加载到缓存中,之后读取数据,直接从缓冲中取,缩短数据读取时间。

    设计需要满足两个条件:1、服务启动时,即可加载;2、定时扫描字典数据表(文件),重新加载数据到缓存。

二、实现

    private Timer timer;

    private Map<String, Map<String, String>> cache = null;

    @PostConstruct
    void init() {       
        timer = new Timer("dictionaryCacheTimer");
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                load();
            }

        }, 1 * 60 * 1000 , 30 * 60 * 1000);
        load();
    }

    @PreDestroy
    void destroy() {
        timer.cancel();
    }

    private void load() {
        Map<String, Map<String, String>> types = Collections.synchronizedMap(new HashMap<String, Map<String, String>>());
        // TODO 读取数据放入 types 中
        synchronized (this) {
            cache = types;
        }
        types = null;
    }

 

posted @ 2014-05-24 09:50  Bruce.Chang.Lee  阅读(443)  评论(0)    收藏  举报