mybatis用memcache做二级缓存

参考自http://www.mybatis.org/memcached-cache/

1.添加依赖
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-memcached</artifactId>
<version>1.0.0</version>
</dependency>
jar包里有个类MemcachedCache实现了mybatis的二级缓存的接口

2.对mybatis进行缓存配置
在需要开启缓存的mapper文件里加上
<cache type="org.mybatis.caches.memcached.MemcachedCache"></cache>
在mybatis的配置文件里开启缓存
<setting name="cacheEnabled" value="true"/>

3.添加memcached的缓存配置文件memcached.properties在类路径下。
org.mybatis.caches.memcached.keyprefix = _mybatis_
org.mybatis.caches.memcached.servers = localhost:11211
org.mybatis.caches.memcached.connectionfactory = net.spy.memcached.DefaultConnectionFactory
org.mybatis.caches.memcached.expiration = 60*60*60
org.mybatis.caches.memcached.asyncget = false
org.mybatis.caches.memcached.timeout = 5
org.mybatis.caches.memcached.timeoutunit = java.util.concurrent.TimeUnit.SECONDS
org.mybatis.caches.memcached.compression =false

4.开启memcached的服务端

添加依赖

<dependency>
<groupId>com.thimbleware.jmemcached</groupId>
<artifactId>jmemcached-core</artifactId>
<version>1.0.0</version>
</dependency>

public class MemcachedServer {

public static void main(String[] args) {
int maxItems = 1024;
long maxBytes = 1024 * 2048;
int idleTime=60*60*1;
boolean binary=false;
final MemCacheDaemon<LocalCacheElement> daemon = new MemCacheDaemon<LocalCacheElement>();
CacheStorage<Key, LocalCacheElement> storage = ConcurrentLinkedHashMap.create(ConcurrentLinkedHashMap.EvictionPolicy.FIFO, maxItems, maxBytes);
daemon.setCache(new CacheImpl(storage));
daemon.setBinary(binary);
daemon.setAddr(new InetSocketAddress("127.0.0.1", 11211));
daemon.setIdleTime(idleTime);
daemon.setVerbose(false);
daemon.start();
}
}

运行main之后,缓存就启动了。

5.开始测试了

public class TestStaff {
private static SqlSessionFactory sqlSessionFactory;
private static Logger logger = LoggerFactory.getLogger(TestStaff.class);
public TestStaff() {
String resource = "mybatis-config.xml";
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}

}
@Test
public void test() {
SqlSession openSession = sqlSessionFactory.openSession();
try{
StaffDao mapper = openSession.getMapper(StaffDao.class);

Staff staff = mapper.getStaff((long)1);

openSession.close();
openSession = sqlSessionFactory.openSession();
mapper = openSession.getMapper(StaffDao.class);
Staff staff1 = mapper.getStaff((long)1);

logger.debug(staff.toString());
logger.debug(staff1.toString());
}finally{
openSession.close();
}
}

}

查询结果如下,一级缓存关闭之后只查询了一次数据库。

 

转载于:https://www.cnblogs.com/brian-csyy/p/7611895.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值