redis扩展ibatis缓存

ibaits缓存介绍:
1、 http://www.cnblogs.com/yongze103/archive/2011/07/25/2116593.html
2、http://blog.csdn.net/woshixuye/article/details/8062038
3、http://www.cnblogs.com/phoebus0501/archive/2011/05/17/2048462.html

redis介绍:
http://blog.csdn.net/u012385190/article/details/53424931

jedis介绍:
Jedis是redis的java版本的客户端实现
http://blog.csdn.net/u012385190/article/details/53464621

下面开始使用ibatis缓存

部分代码:

sqlMapConfig.xml

<!-- 扩展缓存 -->
    <typeAlias alias="CMCF_CACHE" type="com.cmcf.web.base.controller.RedisController" />

顺便提一句,要使用缓存注意SqlMapConfig.xml文件中settings节点配置cacheModelsEnabled为true!

<settings  
    cacheModelsEnabled="true"  
    useStatementNamespaces="true"   
    ...   
/>  

实体类sql.xml

    <!-- 缓存配置 -->
    <cacheModel id="pmcache" readOnly="true" serialize="false" type="CMCF_CACHE">
        <!-- 当下面方法执行时刷新缓存 -->
        <flushOnExecute statement="com.cmcf.model.entity.sf.SfInfoEntity.save" />
        <flushOnExecute statement="com.cmcf.model.entity.sf.SfInfoEntity.insert" />
        <flushOnExecute statement="com.cmcf.model.entity.sf.SfInfoEntity.update" />
        <flushOnExecute statement="com.cmcf.model.entity.sf.SfInfoEntity.delete" />
        <flushOnExecute statement="com.cmcf.model.entity.sf.SfInfoEntity.deleteByIds" />
    </cacheModel>

    <!--利用缓存 配置cacheModel="pmcache"   pmcache为缓存配置的id值-->
    <!-- 根据公司id查询旗下基金信息 -->
    <select id="queryOrgDeputyPro" resultClass="hashmap" cacheModel="pmcache">
        SELECT * FROM sfinfo where id=#id#
    </select>

这样一配置,当数据库调用id为queryOrgDeputyPro的查询时将会在redis中缓存sql语句(调用实现了CacheController的putObject方法),下次再查询会调用getObject方法,同时如果调用SfInfoEntity这个对象的增删改方法会清空redis缓存(调用CacheController的flush方法)。




redis.properties 配置:

redis.pool.maxActive=10000
redis.pool.maxIdle=500
redis.pool.maxWait=1000
redis.pool.testOnBorrow=false
redis.pool.testOnReturn=false
redis.host=你的ip地址
redis.port=6379
redis.db.pk=ztol
redis.password=myRedis




redis java客户端代码

pom.xml

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.8.2</version>
</dependency>

RedisController 类

/*
 * Description: redis扩展ibatis缓存      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.cmcf.web.base.controller;

import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol;

import com.cmcf.utils.SerializeUtil;
import com.ibatis.sqlmap.engine.cache.CacheController;
import com.ibatis.sqlmap.engine.cache.CacheModel;

/**
 * redis扩展ibatis缓存<br>
 * @see [相关类/方法](可选)
 * @since [产品/模块版本] (可选)
 */
public class RedisController implements CacheController {

    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisController.class);

    /**
     * 默认redis属性配置文件
     */
    private static final String DEFAULT_REDIS_PROP = "properties/redis.properties";

    /**
     * 数据库唯一标识
     */
    private String dbPk = "/";

    /**
     * redis java客户端连接池
     */
    private JedisPool pool;


    @Override
    public void flush(CacheModel cacheModel) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.flushDB();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            if (null != jedis) {
                // 释放redis对象
                pool.returnResource(jedis);
            }
        }
    }


    @Override
    public Object getObject(CacheModel cacheModel, Object key) {
        String keyString = key.toString();
        Object value = null;
        Jedis jedis = null;
        try {
            jedis = getJedis();
            byte[] byteArray = jedis.hget(SerializeUtil.serialize(buildId(cacheModel)),
                    SerializeUtil.serialize(keyString));
            if (null != byteArray) {
                value = SerializeUtil.unserialize(byteArray);
                if (CacheModel.NULL_OBJECT.equals(value)) {
                    value = null;
                }
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            if (null != jedis) {
                pool.returnResource(jedis);
            }
        }
        return value;
    }


    @Override
    public void putObject(CacheModel cacheModel, Object key, Object value) {
        String keyString = key.toString();
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.hset(SerializeUtil.serialize(buildId(cacheModel)), SerializeUtil.serialize(keyString),
                    SerializeUtil.serialize(value));
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            if (null != jedis) {
                pool.returnResource(jedis);
            }
        }
    }

    /**
     * 功能描述: <br>
     * 创建id
     */
    private String buildId(CacheModel cacheModel) {
        return this.dbPk + cacheModel.getId();
    }

    @Override
    public Object removeObject(CacheModel cacheModel, Object key) {
        String keyString = key.toString();
        Jedis jedis = null;
        try {
            jedis = getJedis();
            Object result = jedis.expire(SerializeUtil.serialize(keyString), 0);
            if (CacheModel.NULL_OBJECT.equals(result)) {
                return null;
            } else {
                return result;
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return null;
        } finally {
            if (null != jedis) {
                pool.returnResource(jedis);
            }
        }
    }

    @Override
    public void setProperties(Properties props) {
        rebuildProperties(props);
        JedisPoolConfig config = configJedisPoolConfig(props);
        pool = buildJedisPool(props, config);
    }

    /**
     * 功能描述: <br>
     * 重建属性信息,将默认配置进行填充
     */
    private void rebuildProperties(Properties props) {
        Properties defaultProperties = new Properties();
        try {
            defaultProperties.load(RedisController.class.getClassLoader().getResourceAsStream(DEFAULT_REDIS_PROP));
        } catch (Exception ex) {
            LOGGER.warn("load redis.properties failed", ex);
        }
        defaultProperties.putAll(props);
        props.clear();
        props.putAll(defaultProperties);
    }

    /**
     * 功能描述: <br>
     * 构建jedis pool
     */
    private JedisPool buildJedisPool(Properties props, JedisPoolConfig config) {
        String host = props.getProperty("redis.host");
        String portStr = props.getProperty("redis.port");
        // String password = props.getProperty("redis.password");
        int port = Protocol.DEFAULT_PORT;
        if (StringUtils.isNumeric(portStr)) {
            port = Integer.parseInt(portStr);
        }
        int timeout = Protocol.DEFAULT_TIMEOUT;
        String timeoutStr = props.getProperty("redis.timeout");
        if (StringUtils.isNumeric(timeoutStr)) {
            timeout = Integer.parseInt(timeoutStr);
        }
        String dbPkStr = props.getProperty("redis.db.pk", "/");
        if (dbPkStr.endsWith("/")) {
            this.dbPk = dbPkStr;
        } else {
            this.dbPk = dbPkStr + "/";
        }
        // return new JedisPool(config, host, port, timeout, password);
        return new JedisPool(config, host, port, timeout);
    }

    /**
     * 功能描述: <br>
     * 配置jedis pool config
     */
    private JedisPoolConfig configJedisPoolConfig(Properties props) {
        JedisPoolConfig config = new JedisPoolConfig();
        String maxActive = props.getProperty("redis.pool.maxActive");
        if (StringUtils.isNumeric(maxActive)) {
            config.setMaxActive(Integer.valueOf(maxActive));
        }
        String maxIdle = props.getProperty("redis.pool.maxIdle");
        if (StringUtils.isNumeric(maxIdle)) {
            config.setMaxIdle(Integer.valueOf(maxIdle));
        }
        String maxWait = props.getProperty("redis.pool.maxWait");
        if (StringUtils.isNumeric(maxWait)) {
            config.setMaxWait(Long.valueOf(maxWait));
        }
        String testOnBorrow = props.getProperty("redis.pool.testOnBorrow");
        if (StringUtils.isNotBlank(testOnBorrow)) {
            config.setTestOnBorrow(Boolean.valueOf(testOnBorrow));
        }
        String testOnReturn = props.getProperty("redis.pool.testOnReturn");
        if (StringUtils.isNotBlank(testOnReturn)) {
            config.setTestOnReturn(Boolean.valueOf(testOnBorrow));
        }
        String minEvictableIdle = props.getProperty("redis.pool.minEvictableIdle");
        if (StringUtils.isNumeric(minEvictableIdle)) {
            config.setMinEvictableIdleTimeMillis(Long.valueOf(minEvictableIdle));
        }
        String softMinEvictableIdle = props.getProperty("redis.pool.softMinEvictableIdle");
        if (StringUtils.isNumeric(softMinEvictableIdle)) {
            config.setSoftMinEvictableIdleTimeMillis(Long.valueOf(softMinEvictableIdle));
        }
        return config;
    }

    /**
     * 
     * 功能描述: <br>
     * 获取Jedis实例
     */
    private Jedis getJedis() {
        return pool.getResource();
    }
}



SerializeUtil类代码

/**
 * 序列化工具类<br>
 * 使用JDK自带方式进行序列化和反序列化
 */
public class SerializeUtil {

    /**
     * 
     * 功能描述: <br>
     * 序列化 成byte数组
     */
    public static byte[] serialize(Object object) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(object);
        return baos.toByteArray();
    }

    /**
     * 
     * 功能描述: <br>
     * 反序列化
     */
    public static Object unserialize(byte[] byteArray) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
        ObjectInputStream ois = new ObjectInputStream(bais);
        return ois.readObject();
    }
}

ibatis缓存的不是一个对象,而是该sql语句

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值