首页 > 代码库 > java模拟数据库缓存

java模拟数据库缓存

实现缓存一些数据到本地,避免重复查询数据库,对数据库造成压力,代码如下:

package threadLock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class CatheDemo {

    private Map<String, Object> map = new HashMap<String, Object>();
    
    private ReadWriteLock rwl = new ReentrantReadWriteLock(); //定义读写锁
    
    public Object getData(String key){
        rwl.readLock().lock();
        Object value = null;
        try {
            value = map.get(key);
            if (value =http://www.mamicode.com/=  null) {
                rwl.readLock().unlock();
                rwl.writeLock().lock();
                try {
                    if(value =http://www.mamicode.com/= null)
                        value = "dqwdwqd"; //从数据库中查找数据
                } catch (Exception e) {
                    e.printStackTrace();
                }finally{
                    rwl.writeLock().unlock();
                    rwl.readLock().lock();
                }
                
                
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            rwl.readLock().unlock();
        }
        return value;
    }
}

 

java模拟数据库缓存