redis学习总结-redis作为MyBatis的自定义缓存
1、RedisCache.java
package com.houtai.cache; import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; public class RedisCache implements Cache {
private static Log logger = LogFactory.getLog(RedisCache.class);
private Jedis redisClient = createClient();
/** The ReadWriteLock. */
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private String id; public RedisCache(final String id) {
if (id == null) {
throw new IllegalArgumentException("Cache instances require an ID");
}
logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>MybatisRedisCache:id=" + id);
this.id = id;
} public String getId() {
return this.id;
} public int getSize() {
return Integer.valueOf(redisClient.dbSize().toString());
} public void putObject(Object key, Object value) {
logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>putObject:" + key + "=" + value);
redisClient.set(SerializeUtil.serialize(key.toString()), SerializeUtil
.serialize(value));
} public Object getObject(Object key) {
Object value = SerializeUtil.unserialize(redisClient.get(SerializeUtil
.serialize(key.toString())));
logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>getObject:" + key + "=" + value);
return value;
} public Object removeObject(Object key) {
return redisClient.expire(SerializeUtil.serialize(key.toString()), 0);
} public void clear() {
redisClient.flushDB();
} public ReadWriteLock getReadWriteLock() {
return readWriteLock;
} protected static Jedis createClient() {
try {
JedisPool pool = new JedisPool(new JedisPoolConfig(),
"localhost");
return pool.getResource();
} catch (Exception e) {
e.printStackTrace();
}
throw new RuntimeException("初始化连接池错误");
} }
2、序列化与方序列化工具类
package com.houtai.cache; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; /**
*
* @author 作者: wcy
* @version 创建时间:Mar 20, 2015 3:27:39 PM
* @Description: TODO(用于序列化键值对)
*/
public class SerializeUtil { public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
// 序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
} catch (Exception e) {
e.printStackTrace();
}
return null;
} public static Object unserialize(byte[] bytes) {
if (bytes == null)
return null;
ByteArrayInputStream bais = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
3、自定义缓存的入口,继承MyBatis的loggingCache类
package com.houtai.cache;
import org.apache.ibatis.cache.decorators.LoggingCache;
public class LoggingRedisCache extends LoggingCache{
public LoggingRedisCache(String id) {
super(new RedisCache(id));
// TODO Auto-generated constructor stub
}
}
4、同时配置MyBatis的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- 这个配置使全局的映射器启用或禁用缓存 -->
<setting name="cacheEnabled" value="true" />
<!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
<setting name="multipleResultSetsEnabled" value="true" />
<!-- 配置默认的执行器。SIMPLE 执行器没有什么特别之处。REUSE 执行器重用预处理语句。BATCH 执行器重用语句和批量更新 -->
<setting name="defaultExecutorType" value="REUSE" />
<!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 -->
<setting name="lazyLoadingEnabled" value="false" />
<setting name="aggressiveLazyLoading" value="true" />
<!-- <setting name="enhancementEnabled" value="true"/> -->
<!-- 设置超时时间,它决定驱动等待一个数据库响应的时间。 -->
<setting name="defaultStatementTimeout" value="25000" />
</settings>
<typeAliases>
<package name="com.houtai.model" />
</typeAliases> <mappers>
<mapper resource="sqlmap/houtai/accountMapper.xml" />
<mapper resource="sqlmap/houtai/categoryMapper.xml" />
<mapper resource="sqlmap/houtai/goodsMapper.xml" />
<mapper resource="sqlmap/houtai/sorderMapper.xml" />
<mapper resource="sqlmap/houtai/forderMapper.xml" />
</mappers>
</configuration>
5、因为使用MyBatis的二级缓存,所以要缓存的类,必须开启<cache/>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.houtai.model.Account">
<!-- redis缓存 -->
<cache eviction="LRU" type="com.houtai.cache.LoggingRedisCache"/>
<select id="loginAccount" parameterType="account" resultType="account" useCache="true">
select * from account a where a.login=#{login} and a.pass=#{pass}
</select>
</mapper>
6、最后测试通过。
redis学习总结-redis作为MyBatis的自定义缓存的更多相关文章
- Redis学习笔记~Redis主从服务器,读写分离
回到目录 Redis这个Nosql的存储系统一般会被部署到linux系统中,我们可以把它当成是一个数据服务器,对于并发理大时,我们会使用多台服务器充当Redis服务器,这时,各个Redis之间也是分布 ...
- redis学习笔记-redis的安装
Window 下安装 下载地址:https://github.com/MSOpenTech/redis/releases Redis 支持 32 位和 64 位.这个需要根据你系统平台的实际情况选择, ...
- Redis学习-redis概述
最近刚刚接触了redis技术,对此有一些了解,这是简单做一点总结. Redis简介 首先,简单了解一下NoSQL(Not only sql),不要错误的理解为:没有SQL,而是不仅仅是SQL.NoSQ ...
- Redis学习笔记-Redis内部数据结构
Redis内部数据结构 Redis和其他key-value数据库的很大区别是它支持非字符串类型的value值.它支持的value值的类型如下: sds (simple dynamic string) ...
- redis学习之——redis.conf配置(基本)文件学习
# Redis configuration file example # Note on units: when memory size is needed, it is possible to sp ...
- Redis集成到Spring做mybatis做二级缓存
一.原理: 要缓存的 Java 对象必须实现 Serializable 接口,因为 Spring 会将对象先序列化再存入 Redis,比如本文中的 com.defonds.bdp.city.bean. ...
- Redis学习笔记--Redis配置文件Sentinel.conf参数配置详解
redis-sentinel.conf配置项说明如下: 1.port 26379 sentinel监听端口,默认是26379,可以修改. 2.sentinel monitor <master-n ...
- redis学习笔记——Redis过期键的删除策略
Redis过期键的删除策略 对于过期键一般有三种删除策略 定时删除:在设置键的过期时间的同时,创建一个定时器(timer),让定时器在键的过期时间来临时,立即执行对键的删除操作: 惰性删除:放任键过期 ...
- [转载] redis学习入门 Redis 3.2.100
参考博客: https://blog.csdn.net/flyer_tang/article/details/80320974 https://blog.csdn.net/weixin_3077313 ...
随机推荐
- 使用sort对数组中的对象的某个属性进行排序
var data=[ { code: "10004", grade: "5.6", planQuantity: 220, }, { code: "10 ...
- mqtt mosquitto 源码安装
下载地址 ububtu : wget https://codeload.github.com/eclipse/mosquitto/zip/master 安装依赖 sudo apt-get insta ...
- STM32CubeMX HAL库串口+DMA数据发送不定长度数据接收
参考资料:1.ST HAL库官网资料 2.https://blog.csdn.net/u014470361/article/details/79206352#comments 一.STM32CubeM ...
- 【慕课网实战】九、以慕课网日志分析为例 进入大数据 Spark SQL 的世界
即席查询普通查询 Load Data1) RDD DataFrame/Dataset2) Local Cloud(HDFS/S3) 将数据加载成RDDval masterLog = sc.textFi ...
- Linux运行模式
查看运行模式 cat /etc/inittab 0.表示关机模式,不要把默认模式设置成0 1.表示单用户模式 2.表示多用户模式 3.表示命令行模式 4.表示暂未被使用的模式,以后有可能会被使用 5. ...
- 处理Word文档中所有修订
打开现有文档进行编辑 若要打开现有文档,您可以将 Word类实例化,如以下 using 语句所示. 为此,您可以使用Open(String, Boolean) 方法打开具有指定 fileName 的字 ...
- 行业相关的webgl项目
炼钢厂污水处理http://www.hightopo.com/demo/CirculatingWaterPump/index.html智能idc机房http://www.hightopo.com/de ...
- Spring Boot中Web应用的统一异常处理 转载来自翟永超
我们在做Web应用的时候,请求处理过程中发生错误是非常常见的情况.Spring Boot提供了一个默认的映射:/error,当处理中抛出异常之后,会转到该请求中处理,并且该请求有一个全局的错误页面用来 ...
- ES6中的箭头函数和普通函数有什么区别?
1.普通函数中的this总是指向调用它的那个对象, 箭头函数没有自己的this,他的this永远指向其定义环境,任何方法都改变不了其指向,如call().bind().apply().(正是因为它没有 ...
- CS61A Lecture3 Note
本次lec主讲控制流 本文档只列一些py控制流与C不同的地方 print的功能不同 可以print出来None这种东西 重点讲了函数运行机制,我的理解是这样的,在调用函数之前,def会产生一个glo ...