惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

W
WeLiveSecurity
The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
Microsoft Azure Blog
Microsoft Azure Blog
The Register - Security
The Register - Security
Stack Overflow Blog
Stack Overflow Blog
博客园 - 三生石上(FineUI控件)
T
Threat Research - Cisco Blogs
S
SegmentFault 最新的问题
V2EX - 技术
V2EX - 技术
Hacker News: Ask HN
Hacker News: Ask HN
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
P
Proofpoint News Feed
J
Java Code Geeks
Microsoft Security Blog
Microsoft Security Blog
M
MIT News - Artificial intelligence
AI
AI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
P
Proofpoint News Feed
Hacker News - Newest:
Hacker News - Newest: "LLM"
B
Blog
N
News and Events Feed by Topic
N
News | PayPal Newsroom
Google DeepMind News
Google DeepMind News
酷 壳 – CoolShell
酷 壳 – CoolShell
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
WordPress大学
WordPress大学
C
Cybersecurity and Infrastructure Security Agency CISA
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 【当耐特】
U
Unit 42
腾讯CDC
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
The Cloudflare Blog
H
Help Net Security
Recent Announcements
Recent Announcements
P
Privacy & Cybersecurity Law Blog
IT之家
IT之家
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Security Archives - TechRepublic
Security Archives - TechRepublic
L
LINUX DO - 热门话题
Martin Fowler
Martin Fowler
MongoDB | Blog
MongoDB | Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
H
Heimdal Security Blog
博客园 - 聂微东
S
Securelist
大猫的无限游戏
大猫的无限游戏
Cloudbric
Cloudbric
Cisco Talos Blog
Cisco Talos Blog

博客园 - ClawStudio

maven项目,httpclient jar包冲突 mysql5 数据库连接丢失问题,autoReconnect=true不起作用 博文阅读密码验证 - 博客园 org.springframework.web.method.HandlerMethod 与 org.springframework.messaging.handler.HandlerMethod 转换失败 dubbo常见错误 jvm实战-jvm调优 使用http load测试qps 博文阅读密码验证 - 博客园 jvm理论-字节码指令 博文阅读密码验证 - 博客园 jvm理论-字节码指令案例 jvm理论-class文件 jvm理论-常量池-string 博文阅读密码验证 - 博客园 jvm工具 jvm理论-运行时数据区 java nio-理解同步、异步,阻塞和非阻塞 博文阅读密码验证 - 博客园 博文阅读密码验证 - 博客园
真正的mybatis_redis二级缓存
ClawStudio · 2016-09-13 · via 博客园 - ClawStudio

网上流传的代码缓存失效存在严重问题。

思路....以后再细说

目前的方案还不够完美,失效力度控制不够细。

主要代码

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
 
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.ibatis.cache.Cache;
import org.apache.log4j.Logger;


import redis.clients.jedis.Jedis;

 
/*
 * 使用第三方缓存服务器,处理二级缓存
 * zuimao
 */
public class RedisCache implements Cache {
     
    private static final Logger logger = Logger.getLogger(RedisCache.class);
     
    /** The ReadWriteLock. */
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
 
    private final String COMMON_CACHE_KEY = "MYBATIS:";
    private static final String UTF_8 = "utf-8";
  
    /**
     * 按照一定规则标识key
     */
    private String getKey(Object key) {
        StringBuilder accum = new StringBuilder();
        accum.append(COMMON_CACHE_KEY);
        accum.append(this.id).append(":");
        accum.append(DigestUtils.md5Hex(String.valueOf(key)));
        return accum.toString();
    }
  
    /**
     * redis key规则前缀
     */
    private String getKeys() {
        return COMMON_CACHE_KEY + this.id + ":*";
    }
 
    private String id; 
 
    public RedisCache() {
    }
 
    public RedisCache(final String id) {
        if (id == null) {
            throw new IllegalArgumentException("必须传入ID");
        }
        logger.debug("MybatisRedisCache:id=" + id);
        this.id = id;
    }
 
    @Override
    public String getId() {
        return this.id;
    }
 
    @Override
    public int getSize() {
        Jedis jedis = null;
        int result = 0;
        try {
            jedis = RedisStandAloneUtil.getJedisPool().getResource();
            Set<byte[]> keys = jedis.keys(getKeys().getBytes(UTF_8));
            if (null != keys && !keys.isEmpty()) {
                result = keys.size();
            }
            logger.debug(this.id+"---->>>>总缓存数:" + result);
        } catch (Exception e) {
        	 logger.error(e.getMessage(), e);
        } finally {
        	if (jedis != null) {
                jedis.close();
            }
            
        }
        return result;
    }
 
    @Override
    public void putObject(Object key, Object value) {
        Jedis jedis = null;
        try {
            jedis = RedisStandAloneUtil.getJedisPool().getResource();             
            byte[] keys = getKey(key).getBytes(UTF_8);
            jedis.set(keys, SerializeUtil.serialize(value));
            logger.debug("添加缓存--------"+this.id);
            //getSize();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
 
    }
 
    @Override
    public Object getObject(Object key) {
        Jedis jedis = null;
        Object value = null;
        try {
        	jedis = RedisStandAloneUtil.getJedisPool().getResource();
            value = SerializeUtil.unserialize(jedis.get(getKey(key).getBytes(UTF_8)));
            logger.debug("从缓存中获取-----"+this.id);
            //getSize();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return value;
    }
 
    @Override
    public Object removeObject(Object key) {
        Jedis jedis = null;
        Object value = null;
        try {
        	jedis = RedisStandAloneUtil.getJedisPool().getResource();
            value = jedis.del(getKey(key).getBytes(UTF_8));
            logger.debug("LRU算法从缓存中移除-----"+this.id);
            //getSize();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return value;
    }
 
    @Override
    public void clear() {
        Jedis jedis = null;
        try {
        	jedis = RedisStandAloneUtil.getJedisPool().getResource();
            Set<byte[]> keys = jedis.keys(getKeys().getBytes(UTF_8));
            logger.debug("出现CUD操作,清空对应Mapper缓存======>"+keys.size());
            for (byte[] key : keys) {
                jedis.del(key);
            }
            //下面是网上流传的方法,极大的降低系统性能,没起到加入缓存应有的作用,这是不可取的。
            //jedis.flushDB();
            //jedis.flushAll();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }
 
    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }
     
}