mybatis redis 实现二级缓存

来源:互联网 发布:sql server 2008 免费 编辑:程序博客网 时间:2024/05/01 04:58

一、pom.xml中加入依赖

<!-- spring-redis实现 --><dependency>    <groupId>org.springframework.data</groupId>    <artifactId>spring-data-redis</artifactId>    <version>1.6.2.RELEASE</version></dependency><!-- redis客户端jar --><dependency>    <groupId>redis.clients</groupId>    <artifactId>jedis</artifactId>    <version>2.8.0</version></dependency><!-- Ehcache实现,用于参考 --><dependency>    <groupId>org.mybatis</groupId>    <artifactId>mybatis-ehcache</artifactId>    <version>1.0.0</version></dependency>
二、配置文件redis.properties

#IPredis.host=192.168.1.162#端口redis.port=6379  redis.pass=redis.maxIdle=300  redis.maxActive=600  redis.maxWait=1000  redis.testOnBorrow=true #指定redis缓存存储库redis.database=4
三、在applicationContext.xml中引入redis配置

<!-- redis数据源 --><bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"><property name="maxIdle" value="${redis.maxIdle}" /><property name="maxTotal" value="${redis.maxActive}" /><property name="maxWaitMillis" value="${redis.maxWait}" /><property name="testOnBorrow" value="${redis.testOnBorrow}" /></bean><!-- Spring-redis连接池管理工厂 --><bean id="jedisConnectionFactory"class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}"p:pool-config-ref="poolConfig" p:database="${redis.database}"/><!-- 使用中间类解决RedisCache.jedisConnectionFactory的静态注入,从而使MyBatis实现第三方缓存 --><bean id="redisCacheTransfer" class="com.lin.config.redis.RedisCacheTransfer"><property name="jedisConnectionFactory" ref="jedisConnectionFactory" /></bean>

四、创建缓存实现类RedisCache  实现 Cache

public class RedisCache implements Cache {private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);private static JedisConnectionFactory jedisConnectionFactory;private final String id;/** * The {@code ReadWriteLock}. */private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();public RedisCache(final String id) {if (id == null) {throw new IllegalArgumentException("Cache instances require an ID");}logger.debug("MybatisRedisCache:id=" + id);this.id = id;}/** * 在进行 insert update delete 时执行 */@Overridepublic void clear() {JedisConnection connection = null;try {connection = jedisConnectionFactory.getConnection();//删除当前数据库中的所有Key  dbIndex参数 就是指定的库connection.flushDb();//删除所有数据库中的key  //connection.flushAll();} catch (JedisConnectionException e) {e.printStackTrace();} finally {if (connection != null) {connection.close();}}}@Overridepublic String getId() {return this.id;}/** * 从缓存中读取数据 */@Overridepublic Object getObject(Object key) {Object result = null;JedisConnection connection = null;try {connection = jedisConnectionFactory.getConnection();RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();result = serializer.deserialize(connection.get(serializer.serialize(key)));} catch (JedisConnectionException e) {e.printStackTrace();} finally {if (connection != null) {connection.close();}}return result;}@Overridepublic ReadWriteLock getReadWriteLock() {return this.readWriteLock;}@Overridepublic int getSize() {// 获取 缓存key的大小int result = 0;JedisConnection connection = null;try {connection = jedisConnectionFactory.getConnection();result = Integer.valueOf(connection.dbSize().toString());} catch (JedisConnectionException e) {e.printStackTrace();} finally {if (connection != null) {connection.close();}}return result;}/** * 将数据放到缓存中 */@Overridepublic void putObject(Object key, Object value) {JedisConnection connection = null;try {connection = jedisConnectionFactory.getConnection();RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();connection.set(serializer.serialize(key), serializer.serialize(value));//设置缓存数据保存时长connection.expire(serializer.serialize(key), 300);} catch (JedisConnectionException e) {e.printStackTrace();} finally {if (connection != null) {connection.close();}}}@Overridepublic Object removeObject(Object key) {System.out.println("remove key 到了设定时间");JedisConnection connection = null;Object result = null;try {connection = jedisConnectionFactory.getConnection();RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();result = connection.expire(serializer.serialize(key), 0);} catch (JedisConnectionException e) {e.printStackTrace();} finally {if (connection != null) {connection.close();}}return result;}public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {RedisCache.jedisConnectionFactory = jedisConnectionFactory;}

五、创建中间类RedisCacheTransfer

public class RedisCacheTransfer {    @Autowired    public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {        RedisCache.setJedisConnectionFactory(jedisConnectionFactory);    }}
六、加入MyBatis二级缓存
<mapper namespace="com.lin.dao.TopicCcommentInfoMapper" >  <cache type="com.lin.config.redis.RedisCache"/></mapper>

七、配置mybatis.xml

<?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><!-- 配置mybatis的缓存,延迟加载等等一系列属性 --><settings><!-- 全局映射器启用缓存 *主要将此属性设置完成即可 --><setting name="cacheEnabled" value="true" /><!-- 查询时,关闭关联对象即时加载以提高性能 --><setting name="lazyLoadingEnabled" value="false" /><!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 --><setting name="multipleResultSetsEnabled" value="true" /><!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 --><setting name="aggressiveLazyLoading" value="true" /></settings></configuration>

最后测试是否成功:

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = { "classpath:application.xml" })public class RedisTest {//private static final Logger logger = LoggerFactory.getLogger(RedisTest.class);@Autowiredprivate TopicInfoMapper t;/* * 缓存测试 */@Testpublic void testCache2() {//第一次查询TopicInfo top = t.selectByPrimaryKey(310L);System.out.println("==========================1===============");//第一次查询TopicInfo top2 = t.selectByPrimaryKey(309L);System.out.println("==========================2===============");//第二次查询TopicInfo top3 = t.selectByPrimaryKey(310L);System.out.println("==========================3===============");//此时查看4库中是否有数据  推荐使用连接工具 redis desktop manager//测试修改操作 执行到这一步 redis4库中的缓存数据都被删除top.setContent(top.getContent()+1);t.updateByPrimaryKeySelective(top);}}




原创粉丝点击