1、 Memcache和Mybatis整合jar 下载: mybatis-memcached-1.0.0.jar

      官方网站:http://www.mybatis.org/memcached-cache/index.html

      maven项目添加: 

<!-- mybatis整合memcache -->
        <dependency>
            <groupId>org.mybatis.caches</groupId>
                <artifactId>mybatis-memcached</artifactId>
            <version>1.0.0</version>
        </dependency>

2、Mapper文件添加如下语句:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper        PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"  
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="com.xxx.dao.xxx" >
<cache type="org.mybatis.caches.memcached.LoggingMemcachedCache" />
  <resultMap id="xxx" type="com.xxx.xxx.xxx" >
    <id column="ID" property="id" jdbcType="BIGINT" />
  </resultMap>

配置方式分为有日志和无日志两种(自己测试两种方式打印的日志没区别,日志级别DEBUG):

无日志
<cache type="org.mybatis.caches.memcached.MemcachedCache" />

有日志
<cache type="org.mybatis.caches.memcached.LoggingMemcachedCache" />

3、classpath下新建memcached.properties文件,格式如下:

#any string identifier
org.mybatis.caches.memcached.keyprefix=_biz-cache-wk_
#space separated list of ${host}:${port}
org.mybatis.caches.memcached.servers=192.168.0.200:12000
#org.mybatis.caches.memcached.servers=192.168.0.44:12000
#Any class that implementsnet.spy.memcached.ConnectionFactory
org.mybatis.caches.memcached.connectionfactory=net.spy.memcached.DefaultConnectionFactory
#the number of seconds in 30 days    the expiration time (in seconds)
org.mybatis.caches.memcached.expiration=6000
#flag to enable/disable the async get
org.mybatis.caches.memcached.asyncget=false
#the timeout when using async get
org.mybatis.caches.memcached.timeout=5
#the timeout unit when using async get
org.mybatis.caches.memcached.timeoutunit=java.util.concurrent.TimeUnit.SECONDS
#if true, objects will be GZIP compressed before putting them to
org.mybatis.caches.memcached.compression=false

#\u7f13\u5b58\u670d\u52a1\u5668\u5b95\u673a\u540e\u591a\u4e45\u4e0d\u4f7f\u7528memcached \u6beb\u79d2\u4e3a\u5355\u4f4d
#refuse time when connection refused
org.mybatis.caches.memcached.refuseperiod=1000

配置参数说明:

Property  Default  Description
 org.mybatis.caches.memcached.keyprefix  _mybatis_  缓存key的前缀
 org.mybatis.caches.memcached.servers  localhost:11211  memcache地址
 org.mybatis.caches.memcached.connectionfactory  net.spy.memcached.DefaultConnectionFactory  只要实现接口net.spy.memcached.ConnectionFactory
 org.mybatis.caches.memcached.expiration  2592000(30天的秒数)  过期时间单位秒
 org.mybatis.caches.memcached.asyncget  false  是否启用异步读
 org.mybatis.caches.memcached.timeout  5  使用异步读的timeout时间
 org.mybatis.caches.memcached.timeoutunit  java.util.concurrent.TimeUnit.SECONDS   使用异步读的timeout时间单位
 org.mybatis.caches.memcached.compression  false  如果开启,对象在放到memcache前会使用GZIP 压缩

 

源码存在并发量大缓存数据与数据库不一致问题,详情点击:MyBatis与Memcache集成后缓存数据不一致问题