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集成后緩存數據不一致問題