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 ...
随机推荐
- 移动端常见bug
meta基础知识 H5页面窗口自动调整到设备宽度,并禁止用户缩放页面 <meta name="viewport" content="width=device-wid ...
- 很漂亮的PHP验证码(记录)
在提交表单的时候为了防止机器操作或者是恶意的攻击,在填写表单的时候一般都用验证码来过滤掉一些非法提交数据.今天给大家介绍一款超实用超漂亮的PHP验证码库:Captcha. 安装 使用composer: ...
- uni-app 点击切换图标
前端代码: <template> <view> <image src="../../static/pari/buxihuan.png" v-show= ...
- select、poll、epoll
1.概念 select.poll.epoll都是事件触发机制,当等待的事件发生就触发进行处理,用于I/O复用 2.简单例子理解 3.select函数 3.1函数详解 int select(int ma ...
- mysql 截取替换某个字符串
SELECT m.content,o.order_price,o.id,m.id FROM scp_home_msg m INNER JOIN scp_order o ON m.link_id=o.i ...
- vs C++ scanf 不安全
项目->属性-> c/c++->预处理器->预处理器定义->加入下面这句: _CRT_SECURE_NO_DEPRECATE
- (转载)sqlmap用户手册详解
文章转载自 http://www.vuln.cn/2035 当给sqlmap这么一个url (http://www.target.com/sqlmap/mysql/get_int.php?id=1) ...
- 使用 vs code 搭建vue项目(一)
1. 配置环境 1.1. 安装nodejs,下载地址:https://nodejs.org/en/download/. 步骤-..安装完成后,输入node-v,提示如下,则安装完成. 1.2. 安装v ...
- data science学习笔记1
Mutiple Plots on One Graph plt.plot(x, norm.pdf(x)) plt.plot(x, norm.pdf(x, 1.0, 0.2)) #1.0 = mean, ...
- MapGIS数据中心设计器 帮助文档
我以为是数据设计呢..数据设计按钮在哪里??? 数据库设计和管理(没mapgis k9那么好找)(可以编辑sql数据,可以开发吗?)文件中肯定是不行的,要网络发布,肯定是要导入sql数据库中的(或者是 ...