MyBatis系列目录--5. MyBatis一级缓存和二级缓存(redis实现)
1. 一级缓存测试用例
(1) 默认开启,不需要有什么配置
(2) 示意图
(3) 测试代码
- package com.sohu.tv.cache;
- import org.apache.ibatis.session.SqlSession;
- import org.junit.After;
- import org.junit.Before;
- import org.junit.Test;
- import com.sohu.tv.bean.Player;
- import com.sohu.tv.mapper.PlayerDao;
- import com.sohu.tv.test.mapper.BaseTest;
- /**
- * 一级缓存测试
- *
- * @author leifu
- * @Date 2015-8-3
- * @Time 下午9:51:00
- */
- public class FirstCacheTest extends BaseTest {
- private SqlSession sqlSession;
- private SqlSession sqlSessionAnother;
- @Before
- public void before() {
- sqlSession = sessionFactory.openSession(false);
- sqlSessionAnother = sessionFactory.openSession(false);
- }
- @After
- public void after() {
- sqlSession.close();
- sqlSessionAnother.close();
- }
- @Test
- public void test1() throws Exception {
- PlayerDao playerDao = sqlSession.getMapper(PlayerDao.class);
- Player player = playerDao.getPlayerById(1);
- System.out.println(player);
- playerDao = sqlSession.getMapper(PlayerDao.class);
- player = playerDao.getPlayerById(1);
- System.out.println(player);
- playerDao = sqlSessionAnother.getMapper(PlayerDao.class);
- player = playerDao.getPlayerById(1);
- System.out.println(player);
- }
- @Test
- public void test2() throws Exception {
- PlayerDao playerDao = sqlSession.getMapper(PlayerDao.class);
- Player player = playerDao.getPlayerById(1);
- System.out.println(player);
- //1. session清除或者提交
- // sqlSession1.commit();
- // sqlSession.clearCache();
- //2. 增删改查
- // playerDao.savePlayer(new Player(-1, "abcd", 13));
- // playerDao.updatePlayer(new Player(4, "abcd", 13));
- playerDao.deletePlayer(4);
- player = playerDao.getPlayerById(1);
- System.out.println(player);
- }
- }
2、二级缓存(自带 PerpetualCache)
(0) 示意图
(1) 二级缓存需要开启
总配置文件中,二级缓存也是开启的,不需要设置
- <setting name="cacheEnabled" value="true"/>
mapper级别的cache需要开启,在对应的mapper.xml写入
- <!--开启本mapper的二级缓存-->
- <cache/>
(2) 实体类在二级缓存中需要进行序列化,所以所有实体类需要实现Serializable
(3) 示例:
- package com.sohu.tv.cache;
- import org.apache.ibatis.session.SqlSession;
- import org.junit.After;
- import org.junit.Before;
- import org.junit.Test;
- import com.sohu.tv.bean.Player;
- import com.sohu.tv.mapper.PlayerDao;
- import com.sohu.tv.test.mapper.BaseTest;
- /**
- * 二级缓存测试
- *
- * @author leifu
- * @Date 2015-8-3
- * @Time 下午10:10:34
- */
- public class SecondCacheTest extends BaseTest {
- private SqlSession sqlSession1 = sessionFactory.openSession();
- private SqlSession sqlSession2 = sessionFactory.openSession();
- private SqlSession sqlSession3 = sessionFactory.openSession();
- private PlayerDao playerDao1;
- private PlayerDao playerDao2;
- private PlayerDao playerDao3;
- @Before
- public void before() {
- sqlSession1 = sessionFactory.openSession(false);
- sqlSession2 = sessionFactory.openSession(false);
- sqlSession3 = sessionFactory.openSession(false);
- playerDao1 = sqlSession1.getMapper(PlayerDao.class);
- playerDao2 = sqlSession2.getMapper(PlayerDao.class);
- playerDao3 = sqlSession3.getMapper(PlayerDao.class);
- }
- @After
- public void after() {
- sqlSession1.close();
- sqlSession2.close();
- sqlSession3.close();
- }
- @Test
- public void test1() throws Exception {
- int targetId = 1;
- //session1 查询并提交
- Player player1 = playerDao1.getPlayerById(targetId);
- System.out.println("player1: " + player1);
- sqlSession1.commit();
- //session2 命中后,更新并提交清空缓存
- Player player2 = playerDao2.getPlayerById(targetId);
- System.out.println("player2: " + player2);
- player2.setAge(15);
- playerDao2.update(player2);
- sqlSession2.commit();
- //session3 不命中
- Player player3 = playerDao3.getPlayerById(targetId);
- System.out.println("player3: " + player3);
- }
- @Test
- public void test2() throws Exception {
- int one = 1;
- int two = 2;
- //session1 查询并提交
- Player player1 = playerDao1.getPlayerById(one);
- playerDao1.getPlayerById(two);
- System.out.println("player1: " + player1);
- sqlSession1.commit();
- //session2 命中后,更新并提交清空缓存
- Player player2 = playerDao2.getPlayerById(one);
- System.out.println("player2: " + player2);
- player2.setAge(15);
- playerDao2.updatePlayer(player2);
- sqlSession2.commit();
- //session3 不命中
- Player player3 = playerDao3.getPlayerById(two);
- System.out.println("player3: " + player3);
- }
- }
(4) 重要日志:
- 22:24:37.191 [main] DEBUG com.sohu.tv.mapper.PlayerDao - Cache Hit Ratio [com.sohu.tv.mapper.PlayerDao]: 0.0
- 22:24:37.196 [main] DEBUG o.a.i.t.jdbc.JdbcTransaction - Opening JDBC Connection
- 22:24:37.460 [main] DEBUG o.a.i.d.pooled.PooledDataSource - Created connection 1695520324.
- 22:24:37.460 [main] DEBUG o.a.i.t.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@650f9644]
- 22:24:37.463 [main] DEBUG c.s.t.mapper.PlayerDao.getPlayerById - ==> Preparing: select id,name,age from players where id=?
- 22:24:37.520 [main] DEBUG c.s.t.mapper.PlayerDao.getPlayerById - ==> Parameters: 1(Integer)
- 22:24:37.541 [main] DEBUG c.s.t.mapper.PlayerDao.getPlayerById - <== Total: 1
- player1: Player [id=1, name=kaka, age=60]
- 22:24:37.549 [main] DEBUG o.a.i.t.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@650f9644]
- 22:24:37.549 [main] DEBUG o.a.i.t.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@650f9644]
- 22:24:37.549 [main] DEBUG o.a.i.d.pooled.PooledDataSource - Returned connection 1695520324 to pool.
- 22:29:13.203 [main] DEBUG com.sohu.tv.mapper.PlayerDao - Cache Hit Ratio [com.sohu.tv.mapper.PlayerDao]: 0.5
- player3: Player [id=1, name=kaka, age=60]
- 22:29:13.204 [main] DEBUG o.a.i.t.jdbc.JdbcTransaction - Opening JDBC Connection
- 22:29:13.204 [main] DEBUG o.a.i.d.pooled.PooledDataSource - Checked out connection 1695520324 from pool.
- 22:29:13.204 [main] DEBUG o.a.i.t.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@650f9644]
- 22:29:13.205 [main] DEBUG c.s.tv.mapper.PlayerDao.updatePlayer - ==> Preparing: update players set name=?,age=? where id=?
- 22:29:13.207 [main] DEBUG c.s.tv.mapper.PlayerDao.updatePlayer - ==> Parameters: kaka(String), 60(Integer), 1(Integer)
- 22:29:13.208 [main] DEBUG c.s.tv.mapper.PlayerDao.updatePlayer - <== Updates: 1
- 22:29:13.210 [main] DEBUG o.a.i.t.jdbc.JdbcTransaction - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@650f9644]
- 22:29:13.210 [main] DEBUG o.a.i.t.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@650f9644]
- 22:29:13.211 [main] DEBUG o.a.i.t.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@650f9644]
- 22:29:13.211 [main] DEBUG o.a.i.d.pooled.PooledDataSource - Returned connection 1695520324 to pool.
- 22:29:13.211 [main] DEBUG com.sohu.tv.mapper.PlayerDao - Cache Hit Ratio [com.sohu.tv.mapper.PlayerDao]: 0.3333333333333333
- 22:29:13.211 [main] DEBUG o.a.i.t.jdbc.JdbcTransaction - Opening JDBC Connection
- 22:29:13.212 [main] DEBUG o.a.i.d.pooled.PooledDataSource - Checked out connection 1695520324 from pool.
- 22:29:13.212 [main] DEBUG o.a.i.t.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@650f9644]
- 22:29:13.212 [main] DEBUG c.s.t.mapper.PlayerDao.getPlayerById - ==> Preparing: select id,name,age from players where id=?
- 22:29:13.213 [main] DEBUG c.s.t.mapper.PlayerDao.getPlayerById - ==> Parameters: 1(Integer)
- 22:29:13.214 [main] DEBUG c.s.t.mapper.PlayerDao.getPlayerById - <== Total: 1
- player2: Player [id=1, name=kaka, age=60]
- 22:29:13.215 [main] DEBUG o.a.i.t.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@650f9644]
- 22:29:13.216 [main] DEBUG o.a.i.t.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@650f9644]
- 22:29:13.216 [main] DEBUG o.a.i.d.pooled.PooledDataSource - Returned connection 1695520324 to pool.
3、二级缓存(Redis版)
(1) redis使用一个简单的单点实例作为数据源:
引入jedis pom依赖:
- <jedis.version>2.8.0</jedis.version>
- <protostuff.version>1.0.8</protostuff.version>
- <dependency>
- <groupId>redis.clients</groupId>
- <artifactId>jedis</artifactId>
- <version>${jedis.version}</version>
- </dependency>
- <dependency>
- <groupId>com.dyuproject.protostuff</groupId>
- <artifactId>protostuff-runtime</artifactId>
- <version>${protostuff.version}</version>
- </dependency>
- <dependency>
- <groupId>com.dyuproject.protostuff</groupId>
- <artifactId>protostuff-core</artifactId>
- <version>${protostuff.version}</version>
- </dependency>
jedis获取工具(使用jedispool)
- package com.sohu.tv.redis;
- import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import redis.clients.jedis.JedisPool;
- /**
- * jedisPool获取工具
- *
- * @author leifu
- * @Date 2015年8月4日
- * @Time 上午9:01:45
- */
- public class RedisStandAloneUtil {
- private final static Logger logger = LoggerFactory.getLogger(RedisStandAloneUtil.class);
- /**
- * jedis连接池
- */
- private static JedisPool jedisPool;
- /**
- * redis-host
- */
- private final static String REDIS_HOST = "10.10.xx.xx";
- /**
- * redis-port
- */
- private final static int REDIS_PORT = 6384;
- static {
- try {
- jedisPool = new JedisPool(new GenericObjectPoolConfig(), REDIS_HOST, REDIS_PORT);
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- }
- }
- public static JedisPool getJedisPool() {
- return jedisPool;
- }
- public static void main(String[] args) {
- System.out.println(RedisStandAloneUtil.getJedisPool().getResource().info());
- }
- }
(2) 如果自己实现mybatis的二级缓存,需要实现org.apache.ibatis.cache.Cache接口,已经实现的有如下:
序列化相关工具代码:
- package com.sohu.tv.redis.serializable;
- import com.dyuproject.protostuff.LinkedBuffer;
- import com.dyuproject.protostuff.ProtostuffIOUtil;
- import com.dyuproject.protostuff.Schema;
- import com.dyuproject.protostuff.runtime.RuntimeSchema;
- import java.util.concurrent.ConcurrentHashMap;
- public class ProtostuffSerializer {
- private static ConcurrentHashMap<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<Class<?>, Schema<?>>();
- public <T> byte[] serialize(final T source) {
- VO<T> vo = new VO<T>(source);
- final LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
- try {
- final Schema<VO> schema = getSchema(VO.class);
- return serializeInternal(vo, schema, buffer);
- } catch (final Exception e) {
- throw new IllegalStateException(e.getMessage(), e);
- } finally {
- buffer.clear();
- }
- }
- public <T> T deserialize(final byte[] bytes) {
- try {
- Schema<VO> schema = getSchema(VO.class);
- VO vo = deserializeInternal(bytes, schema.newMessage(), schema);
- if (vo != null && vo.getValue() != null) {
- return (T) vo.getValue();
- }
- } catch (final Exception e) {
- throw new IllegalStateException(e.getMessage(), e);
- }
- return null;
- }
- private <T> byte[] serializeInternal(final T source, final Schema<T> schema, final LinkedBuffer buffer) {
- return ProtostuffIOUtil.toByteArray(source, schema, buffer);
- }
- private <T> T deserializeInternal(final byte[] bytes, final T result, final Schema<T> schema) {
- ProtostuffIOUtil.mergeFrom(bytes, result, schema);
- return result;
- }
- private static <T> Schema<T> getSchema(Class<T> clazz) {
- @SuppressWarnings("unchecked")
- Schema<T> schema = (Schema<T>) cachedSchema.get(clazz);
- if (schema == null) {
- schema = RuntimeSchema.createFrom(clazz);
- cachedSchema.put(clazz, schema);
- }
- return schema;
- }
- }
- package com.sohu.tv.redis.serializable;
- import java.io.Serializable;
- public class VO<T> implements Serializable {
- private T value;
- public VO(T value) {
- this.value = value;
- }
- public VO() {
- }
- public T getValue() {
- return value;
- }
- @Override
- public String toString() {
- return "VO{" +
- "value=" + value +
- '}';
- }
- }
Redis需要自己来实现,代码如下:
- package com.sohu.tv.redis;
- import java.util.concurrent.locks.ReadWriteLock;
- import java.util.concurrent.locks.ReentrantReadWriteLock;
- import org.apache.ibatis.cache.Cache;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import redis.clients.jedis.Jedis;
- import redis.clients.jedis.serializable.ProtostuffSerializer;
- /**
- * mybatis redis实现
- *
- * @author leifu
- * @Date 2015年8月4日
- * @Time 上午9:12:37
- */
- public class MybatisRedisCache implements Cache {
- private static Logger logger = LoggerFactory.getLogger(MybatisRedisCache.class);
- private String id;
- private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
- private final ProtostuffSerializer protostuffSerializer = new ProtostuffSerializer();
- public MybatisRedisCache(final String id) {
- if (logger.isInfoEnabled()) {
- logger.info("============ MybatisRedisCache id {} ============", id);
- }
- if (id == null) {
- throw new IllegalArgumentException("Cache instances require an ID");
- }
- this.id = id;
- }
- @Override
- public String getId() {
- return this.id;
- }
- @Override
- public int getSize() {
- Jedis jedis = null;
- int size = -1;
- try {
- jedis = RedisStandAloneUtil.getJedisPool().getResource();
- size = Integer.valueOf(jedis.dbSize().toString());
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- } finally {
- if (jedis != null) {
- jedis.close();
- }
- }
- return size;
- }
- @Override
- public void putObject(Object key, Object value) {
- if (logger.isInfoEnabled()) {
- logger.info("============ putObject key: {}, value: {} ============", key, value);
- }
- Jedis jedis = null;
- try {
- jedis = RedisStandAloneUtil.getJedisPool().getResource();
- byte[] byteKey = protostuffSerializer.serialize(key);
- byte[] byteValue = protostuffSerializer.serialize(value);
- jedis.set(byteKey, byteValue);
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- } finally {
- if (jedis != null) {
- jedis.close();
- }
- }
- }
- @Override
- public Object getObject(Object key) {
- if (logger.isInfoEnabled()) {
- logger.info("============ getObject key: {}============", key);
- }
- Object object = null;
- Jedis jedis = null;
- try {
- jedis = RedisStandAloneUtil.getJedisPool().getResource();
- byte[] bytes = jedis.get(protostuffSerializer.serialize(key));
- if (bytes != null) {
- object = protostuffSerializer.deserialize(bytes);
- }
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- } finally {
- if (jedis != null) {
- jedis.close();
- }
- }
- return object;
- }
- @Override
- public Object removeObject(Object key) {
- if (logger.isInfoEnabled()) {
- logger.info("============ removeObject key: {}============", key);
- }
- String result = "success";
- Jedis jedis = null;
- try {
- jedis = RedisStandAloneUtil.getJedisPool().getResource();
- jedis.del(String.valueOf(key));
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- } finally {
- if (jedis != null) {
- jedis.close();
- }
- }
- return result;
- }
- @Override
- public void clear() {
- if (logger.isInfoEnabled()) {
- logger.info("============ start clear cache ============");
- }
- String result = "fail";
- Jedis jedis = null;
- try {
- jedis = RedisStandAloneUtil.getJedisPool().getResource();
- result = jedis.flushAll();
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- } finally {
- if (jedis != null) {
- jedis.close();
- }
- }
- if (logger.isInfoEnabled()) {
- logger.info("============ end clear cache result is {}============", result);
- }
- }
- @Override
- public ReadWriteLock getReadWriteLock() {
- return readWriteLock;
- }
- }
(3) mapper配置中加入自定义redis二级缓存:
- <cache type="com.sohu.tv.redis.MybatisRedisCache"/>
(4) 单元测试同第二节
MyBatis系列目录--5. MyBatis一级缓存和二级缓存(redis实现)的更多相关文章
- mybatis基础系列(四)——关联查询、延迟加载、一级缓存与二级缓存
关本文是Mybatis基础系列的第四篇文章,点击下面链接可以查看前面的文章: mybatis基础系列(三)——动态sql mybatis基础系列(二)——基础语法.别名.输入映射.输出映射 mybat ...
- MyBatis 系列五 之 延迟加载、一级缓存、二级缓存设置
MyBatis的延迟加载.一级缓存.二级缓存设置 首先我们必须分清延迟加载的适用对象 延迟加载 MyBatis中的延迟加载,也称为懒加载,是指在进行关联查询时,按照设置延迟加载规则推迟对关联对象的se ...
- mybatis 详解(九)------ 一级缓存、二级缓存
上一章节,我们讲解了通过mybatis的懒加载来提高查询效率,那么除了懒加载,还有什么方法能提高查询效率呢?这就是我们本章讲的缓存. mybatis 为我们提供了一级缓存和二级缓存,可以通过下图来理解 ...
- Mybatis第八篇【一级缓存、二级缓存、与ehcache整合】
Mybatis缓存 缓存的意义 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题. myba ...
- MyBatis 一级缓存、二级缓存全详解(一)
目录 MyBatis 一级缓存.二级缓存全详解(一) 什么是缓存 什么是MyBatis中的缓存 MyBatis 中的一级缓存 初探一级缓存 探究一级缓存是如何失效的 一级缓存原理探究 还有其他要补充的 ...
- mybatis源码学习:一级缓存和二级缓存分析
目录 零.一级缓存和二级缓存的流程 一级缓存总结 二级缓存总结 一.缓存接口Cache及其实现类 二.cache标签解析源码 三.CacheKey缓存项的key 四.二级缓存TransactionCa ...
- Mybatis 一级缓存和二级缓存的使用
目录 Mybatis缓存 一级缓存 二级缓存 缓存原理 Mybatis缓存 官方文档:https://mybatis.org/mybatis-3/zh/sqlmap-xml.html#cache My ...
- Mybatis 一级缓存和二级缓存原理区别 (图文详解)
Java面试经常问到Mybatis一级缓存和二级缓存,今天就给大家重点详解Mybatis一级缓存和二级缓存原理与区别@mikechen Mybatis缓存 缓存就是内存中的数据,常常来自对数据库查询结 ...
- [原创]关于mybatis中一级缓存和二级缓存的简单介绍
关于mybatis中一级缓存和二级缓存的简单介绍 mybatis的一级缓存: MyBatis会在表示会话的SqlSession对象中建立一个简单的缓存,将每次查询到的结果结果缓存起来,当下次查询的时候 ...
随机推荐
- Swift基础之UITabBarController(这是在之前UITableView中直接添加的)
这些基础内容基本已经可以搭建项目框架,剩下的就是一些优化,细节和数据请求问题,慢慢更新.... 在AppDelegate中创建方法 //创建方法执行UITabBarController func cr ...
- 【一天一道LeetCode】#25. Reverse Nodes in k-Group
一天一道LeetCode系列 (一)题目 Given a linked list, reverse the nodes of a linked list k at a time and return ...
- android自定义view之---组合view
最近工作比较轻松,没有什么事情干,于是进入高产模式(呃....高产似xx). 应该很多童鞋对自定义view这个东西比较抵触,可能是听网上说view比较难吧,其实自定义view并没有很难 自定义view ...
- How to Simulate the Price Order or Price Line Function using API QP_PREQ_PUB.PRICE_REQUEST Includes
How to Simulate the Price Order or Price Line Function using API QP_PREQ_PUB.PRICE_REQUEST Includes ...
- Callable与Future
本文可作为传智播客<张孝祥-Java多线程与并发库高级应用>的学习笔记. 在前面写的代码中,所有的任务执行也就执行了,run方法的返回值为空. 这一节我们说的Callable就是一个可以带 ...
- 苹果新的编程语言 Swift 语言进阶(十)--类的继承
一.类的继承 类能够从其它类继承方法.属性以及其它特性,当一个类从另外的类继承时,继承的类称为子类,它继承的类称为超类.在Swift中,继承是类区别与其它类型(结构.枚举)的基础行为. 1.1 .类的 ...
- C++实现双链表
#include <iostream> using namespace std ; #define NR(x) (sizeof(x)/sizeof(x[0])) class node { ...
- (python3爬虫实战-第一篇)利用requests+正则抓取猫眼电影热映口碑榜
今天是个值得纪念了日子,我终于在博客园上发表自己的第一篇博文了.作为一名刚刚开始学习python网络爬虫的爱好者,后期本人会定期发布自己学习过程中的经验与心得,希望各位技术大佬批评指正.以下是我自己做 ...
- Viavdo&ISE&Quartus II级联Modelsim级联仿真
博主一直致力寻找高效的工作方式,所以一直喜欢折腾软件,从刚开始只用软件IDE自带的编辑器,到Notepad++,再到后来的Vim,从用ISE14.7自带的Isim仿真,到发现更好的Modelsim,再 ...
- python---内置模块
时间模块 时间分为三种类型:时间戳,结构化时间,格式化时间 #时间模块,time import time #时间戳 x = time.time() time.gmtime() #将时间戳转换成UTC时 ...