首先安装 memecached 服务端:
之前写过的 文章,centos 安装memcached服务 :
http://toeo.iteye.com/blog/1240607
然后 在 前几天的 弄的 hibernate search 基础上,再添加 memcached 缓存。
因为 hibernate search 虽然 建立了索引。查询速度快了。。但是依然要 load 数据。
证据就是 可以看到搜索如果有结果 肯定会执行 hql 将数据一次都查询出来。
Hibernate: select this_.id as id0_0_, this_.city as city0_0_, this_.passwd as passwd0_0_, this_.user_name as user4_0_0_ from user_info this_ where (this_.id in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?))
当然我觉得 也可以配置 成 直接 将 索引里面的数据 转换成 bean 返回。
但是 有个问题就是。一般是针对 文章进行索引。
要再继续 将文章的内容也添加到索引里面的话这样 ,索引文件会很大。重建索引会慢。(以后可以实验下)
对于文章来说。里面还会有很多 html 代码。放到 索引里面总觉得不太合适。。索引应该尽量小,才可以保证查询速度。
至于将文章放到 memcahed 里面好像也不太好。多了也会变大。但现在内存都是白菜价。很便宜。
所以考虑 还是 弄个 memecached 吧。
再有考虑到将来拆分 项目。弄个集群啥的。。memcached 方便的很。
要用到的开源项目:
http://code.google.com/p/hibernate-memcached/
hibernate memcached 版本 1.2.2
http://code.google.com/p/spymemcached/
因为 hibernate memcached 要用到这个项目 版本 2.7.3
添加pom 我也把 原文件 添加进来了。 。遇到问题的时候可以看看。
<!-- 添加 hibernate memecached --> <dependency> <groupId>hibernate-memcached</groupId> <artifactId>hibernate-memcached</artifactId> <version>1.2.2</version> <scope>system</scope> <systemPath>${basedir}/lib/hibernate-memcached-1.2.2.jar</systemPath> </dependency> <dependency> <groupId>hibernate-memcached-sources</groupId> <artifactId>hibernate-memcached-sources</artifactId> <version>1.2.2</version> <scope>system</scope> <systemPath>${basedir}/lib/hibernate-memcached-1.2.2-sources.jar</systemPath> </dependency> <dependency> <groupId>spymemcached-sources</groupId> <artifactId>spymemcached-sources</artifactId> <version>2.7.3</version> <scope>system</scope> <systemPath>${basedir}/lib/spymemcached-2.7.3-sources.jar</systemPath> </dependency> <dependency> <groupId>spymemcached</groupId> <artifactId>spymemcached</artifactId> <version>2.7.3</version> <scope>system</scope> <systemPath>${basedir}/lib/spymemcached-2.7.3.jar</systemPath> </dependency>
修改 pojo 类:
package com.freewebsys.demo.pojo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.search.annotations.Analyzer; import org.hibernate.search.annotations.DocumentId; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Index; import org.hibernate.search.annotations.Indexed; import org.hibernate.search.annotations.Store; import org.wltea.analyzer.lucene.IKAnalyzer; @Entity @Table(name = "user_info") @Indexed @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class UserInfo implements java.io.Serializable { private Long id; private String userName; private String passwd; private String city; private String content; public UserInfo() { } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", unique = true, nullable = false) @DocumentId public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name = "user_name", unique = false, nullable = true, length = 100) @Field(name = "user_name", index = Index.TOKENIZED, store = Store.YES) public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @Column(name = "passwd", unique = false, nullable = true, length = 100) @Field(name = "passwd", index = Index.TOKENIZED, store = Store.YES) public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } @Column(name = "city", unique = false, nullable = true, length = 100) @Field(name = "city", index = Index.TOKENIZED, store = Store.YES) public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Column(name = "content", unique = false, nullable = true, length = 4000) @Field(name = "content", index = Index.TOKENIZED, store = Store.YES, analyzer = @Analyzer(impl = IKAnalyzer.class)) public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { return "UserInfo [id=" + id + ", userName=" + userName + ", passwd=" + passwd + ", city=" + city + ", content=" + content + "]"; } }
在pojo 里面添加标注:
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
这样就可以缓存数据了。
然后
安装 官方的配置文件:
http://code.google.com/p/hibernate-memcached/wiki/Configuration
如果启动报错:
java.net.ConnectException: Connection refused: no further information at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) at sun.nio.ch.SocketChannelImpl.finishConnect(Unknown Source) at net.spy.memcached.MemcachedConnection.handleIO(MemcachedConnection.java:407) at net.spy.memcached.MemcachedConnection.handleIO(MemcachedConnection.java:275) at net.spy.memcached.MemcachedClient.run(MemcachedClient.java:2030) 2011-11-30 09:56:38.632 WARN net.spy.memcached.MemcachedConnection: Closing, and reopening {QA sa=localhost/127.0.0.1:11211, #Rops=0, #Wops=1, #iq=0, topRop=null, topWop=Cmd: get Keys: com.freewebsys.demo.pojo.UserInfo:0:349 Exp: 0, toWrite=0, interested=0}, attempt 1. 2011-11-30 09:56:38.985 WARN net.spy.memcached.MemcachedConnection: Could not redistribute to another node, retrying primary node for com.freewebsys.demo.pojo.UserInfo:0:349. 2011-11-30 09:56:38.986 WARN net.spy.memcached.MemcachedConnection: Could not redistribute to another node, retrying primary node for com.freewebsys.demo.pojo.UserInfo:0:346. 2011-11-30 09:56:39.988 WARN net.spy.memcached.MemcachedConnection: Could not redistribute to another node, retrying primary node for com.freewebsys.demo.pojo.UserInfo:0:346. 2011-11-30 09:56:39.988 WARN net.spy.memcached.MemcachedConnection: Could not redistribute to another node, retrying primary node for com.freewebsys.demo.pojo.UserInfo:0:342. 2011-11-30 09:56:40.989 WARN net.spy.memcached.MemcachedConnection: Could not redistribute to another node, retrying primary node for com.freewebsys.demo.pojo.UserInfo:0:342. 2011-11-30 09:56:40.990 WARN net.spy.memcached.MemcachedConnection: Could not redistribute to another node, retrying primary node for com.freewebsys.demo.pojo.UserInfo:0:340. 2011-11-30 09:56:41.991 WARN net.spy.memcached.MemcachedConnection: Could not redistribute to another node, retrying primary node for com.freewebsys.demo.pojo.UserInfo:0:340. 2011-11-30 09:56:41.992 WARN net.spy.memcached.MemcachedConnection: Could not redistribute to another node, retrying primary node for com.freewebsys.demo.pojo.UserInfo:0:339. 2011-11-30 09:56:42.633 INFO net.spy.memcached.MemcachedConnection: Reconnecting {QA sa=localhost/127.0.0.1:11211, #Rops=0, #Wops=9, #iq=0, topRop=null, topWop=Cmd: get Keys: com.freewebsys.demo.pojo.UserInfo:0:349 Exp: 0, toWrite=0, interested=0} 2011-11-30 09:56:42.993 WARN net.spy.memcached.MemcachedConnection: Could not redistribute to another node, retrying primary node for com.freewebsys.demo.pojo.UserInfo:0:339. 2011-11-30 09:56:42.993 WARN net.spy.memcached.MemcachedConnection: Could not redistribute to another node, retrying primary node for com.freewebsys.demo.pojo.UserInfo:0:338. 2011-11-30 09:56:43.634 INFO net.spy.memcached.MemcachedConnection: Connection state changed for sun.nio.ch.SelectionKeyImpl@bdd2e7 2011-11-30 09:56:43.634 INFO net.spy.memcached.MemcachedConnection: Reconnecting due to failure to connect to {QA sa=localhost/127.0.0.1:11211, #Rops=0, #Wops=11, #iq=0, topRop=null, topWop=Cmd: get Keys: com.freewebsys.demo.pojo.UserInfo:0:349 Exp: 0, toWrite=0, interested=0} java.net.ConnectException: Connection refused: no further information
说明 memcached 服务没有启动并 或者没有访问到。
如果 日志 信息为:
2011-11-30 10:05:03.906 INFO net.spy.memcached.MemcachedConnection: Added {QA sa=localhost/127.0.0.1:11211, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue 2011-11-30 10:05:03.907 INFO net.spy.memcached.MemcachedConnection: Connection state changed for sun.nio.ch.SelectionKeyImpl@1933acb
说明已经开始往 memecache 里面添加数据了。
测试代码:
System.out.println("##################第1次查询开始:"); List<UserInfo> list = userInfoService.findAllUserInfo(); System.out.println("##################查询结束list size:" + list.size()); System.out.println("##################第2次查询开始:"); list = userInfoService.findAllUserInfo(); System.out.println("##################查询结束list size:" + list.size()); System.out.println("##################第3次查询开始:"); list = userInfoService.findAllUserInfo(); System.out.println("##################查询结束list size:" + list.size()); System.out.println("##################第4次查询开始:"); list = userInfoService.findAllUserInfo(); System.out.println("##################查询结束list size:" + list.size()); System.out.println("##################第5次查询开始:"); list = userInfoService.findAllUserInfo(); System.out.println("##################查询结束list size:" + list.size());
连续查询多次。将数据全部查询出来:数据只有两条记录。需要查询多次才可以看出效果。
开启 hibernate 日志
# Direct log messages to a log file log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=./freewebsys.log log4j.appender.file.MaxFileSize=1MB log4j.appender.file.MaxBackupIndex=1 log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n # Direct log messages to stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n # Root logger option log4j.rootLogger=INFO, file, stdout # Log everything. Good for troubleshooting #log4j.logger.org.hibernate=DEBUG log4j.logger.com.googlecode.hibernate.memcached=DEBUG # Log all JDBC parameters #log4j.logger.org.hibernate.type=ALL
查看hibernate 日志:可以看出缓存已经使:
##################第1次查询开始:
17:47:58,349 DEBUG HashCodeKeyStrategy:12 - Transformed key [sql: select userinfo0_.id as id0_, userinfo0_.city as city0_, userinfo0_.content as content0_, userinfo0_.passwd as passwd0_, userinfo0_.user_name as user5_0_ from user_info userinfo0_; parameters: ; named parameters: {}] to hashCode [-129599688]
17:47:58,349 DEBUG HashCodeKeyStrategy:41 - Final cache key: [org.hibernate.cache.StandardQueryCache:0:-129599688]
17:47:58,349 DEBUG MemcachedCache:115 - Memcache.get(org.hibernate.cache.StandardQueryCache:0:-129599688)
17:47:58,349 DEBUG SpyMemcache:31 - MemcachedClient.get(org.hibernate.cache.StandardQueryCache:0:-129599688)
Hibernate: select userinfo0_.id as id0_, userinfo0_.city as city0_, userinfo0_.content as content0_, userinfo0_.passwd as passwd0_, userinfo0_.user_name as user5_0_ from user_info userinfo0_
这里没有数据查询了下全部数据。
17:47:58,378 DEBUG HashCodeKeyStrategy:12 - Transformed key [com.freewebsys.demo.pojo.UserInfo#380] to hashCode [380]
17:47:58,378 DEBUG HashCodeKeyStrategy:41 - Final cache key: [com.freewebsys.demo.pojo.UserInfo:0:380]
17:47:58,378 DEBUG MemcachedCache:115 - Memcache.get(com.freewebsys.demo.pojo.UserInfo:0:380)
17:47:58,378 DEBUG SpyMemcache:31 - MemcachedClient.get(com.freewebsys.demo.pojo.UserInfo:0:380)
17:47:58,380 DEBUG HashCodeKeyStrategy:12 - Transformed key [com.freewebsys.demo.pojo.UserInfo#380] to hashCode [380]
17:47:58,380 DEBUG HashCodeKeyStrategy:41 - Final cache key: [com.freewebsys.demo.pojo.UserInfo:0:380]
17:47:58,380 DEBUG MemcachedCache:150 - Memcache.set(com.freewebsys.demo.pojo.UserInfo:0:380)
17:47:58,380 DEBUG SpyMemcache:49 - MemcachedClient.set(com.freewebsys.demo.pojo.UserInfo:0:380)
17:47:58,386 DEBUG HashCodeKeyStrategy:12 - Transformed key [com.freewebsys.demo.pojo.UserInfo#379] to hashCode [379]
17:47:58,386 DEBUG HashCodeKeyStrategy:41 - Final cache key: [com.freewebsys.demo.pojo.UserInfo:0:379]
17:47:58,386 DEBUG MemcachedCache:115 - Memcache.get(com.freewebsys.demo.pojo.UserInfo:0:379)
17:47:58,386 DEBUG SpyMemcache:31 - MemcachedClient.get(com.freewebsys.demo.pojo.UserInfo:0:379)
17:47:58,387 DEBUG HashCodeKeyStrategy:12 - Transformed key [com.freewebsys.demo.pojo.UserInfo#379] to hashCode [379]
17:47:58,388 DEBUG HashCodeKeyStrategy:41 - Final cache key: [com.freewebsys.demo.pojo.UserInfo:0:379]
17:47:58,388 DEBUG MemcachedCache:150 - Memcache.set(com.freewebsys.demo.pojo.UserInfo:0:379)
17:47:58,388 DEBUG SpyMemcache:49 - MemcachedClient.set(com.freewebsys.demo.pojo.UserInfo:0:379)
17:47:58,390 DEBUG HashCodeKeyStrategy:12 - Transformed key [sql: select userinfo0_.id as id0_, userinfo0_.city as city0_, userinfo0_.content as content0_, userinfo0_.passwd as passwd0_, userinfo0_.user_name as user5_0_ from user_info userinfo0_; parameters: ; named parameters: {}] to hashCode [-129599688]
17:47:58,390 DEBUG HashCodeKeyStrategy:41 - Final cache key: [org.hibernate.cache.StandardQueryCache:0:-129599688]
17:47:58,390 DEBUG MemcachedCache:150 - Memcache.set(org.hibernate.cache.StandardQueryCache:0:-129599688)
17:47:58,390 DEBUG SpyMemcache:49 - MemcachedClient.set(org.hibernate.cache.StandardQueryCache:0:-129599688)
##################查询结束list size:2
##################第2次查询开始:
17:47:58,397 DEBUG HashCodeKeyStrategy:12 - Transformed key [sql: select userinfo0_.id as id0_, userinfo0_.city as city0_, userinfo0_.content as content0_, userinfo0_.passwd as passwd0_, userinfo0_.user_name as user5_0_ from user_info userinfo0_; parameters: ; named parameters: {}] to hashCode [-129599688]
17:47:58,397 DEBUG HashCodeKeyStrategy:41 - Final cache key: [org.hibernate.cache.StandardQueryCache:0:-129599688]
17:47:58,397 DEBUG MemcachedCache:115 - Memcache.get(org.hibernate.cache.StandardQueryCache:0:-129599688)
17:47:58,397 DEBUG SpyMemcache:31 - MemcachedClient.get(org.hibernate.cache.StandardQueryCache:0:-129599688)
17:47:58,400 DEBUG HashCodeKeyStrategy:12 - Transformed key [user_info] to hashCode [339204258]
17:47:58,401 DEBUG HashCodeKeyStrategy:41 - Final cache key: [org.hibernate.cache.UpdateTimestampsCache:0:339204258]
17:47:58,401 DEBUG MemcachedCache:115 - Memcache.get(org.hibernate.cache.UpdateTimestampsCache:0:339204258)
17:47:58,401 DEBUG SpyMemcache:31 - MemcachedClient.get(org.hibernate.cache.UpdateTimestampsCache:0:339204258)
17:47:58,405 DEBUG HashCodeKeyStrategy:12 - Transformed key [com.freewebsys.demo.pojo.UserInfo#380] to hashCode [380]
17:47:58,405 DEBUG HashCodeKeyStrategy:41 - Final cache key: [com.freewebsys.demo.pojo.UserInfo:0:380]
17:47:58,405 DEBUG MemcachedCache:115 - Memcache.get(com.freewebsys.demo.pojo.UserInfo:0:380)
17:47:58,405 DEBUG SpyMemcache:31 - MemcachedClient.get(com.freewebsys.demo.pojo.UserInfo:0:380)
Hibernate: select userinfo0_.id as id0_0_, userinfo0_.city as city0_0_, userinfo0_.content as content0_0_, userinfo0_.passwd as passwd0_0_, userinfo0_.user_name as user5_0_0_ from user_info userinfo0_ where userinfo0_.id=?
有一个数据 没有命中 请求了下 get 查询。
17:47:58,409 DEBUG HashCodeKeyStrategy:12 - Transformed key [com.freewebsys.demo.pojo.UserInfo#380] to hashCode [380]
17:47:58,409 DEBUG HashCodeKeyStrategy:41 - Final cache key: [com.freewebsys.demo.pojo.UserInfo:0:380]
17:47:58,409 DEBUG MemcachedCache:115 - Memcache.get(com.freewebsys.demo.pojo.UserInfo:0:380)
17:47:58,409 DEBUG SpyMemcache:31 - MemcachedClient.get(com.freewebsys.demo.pojo.UserInfo:0:380)
17:47:58,410 DEBUG HashCodeKeyStrategy:12 - Transformed key [com.freewebsys.demo.pojo.UserInfo#379] to hashCode [379]
17:47:58,410 DEBUG HashCodeKeyStrategy:41 - Final cache key: [com.freewebsys.demo.pojo.UserInfo:0:379]
17:47:58,411 DEBUG MemcachedCache:115 - Memcache.get(com.freewebsys.demo.pojo.UserInfo:0:379)
17:47:58,411 DEBUG SpyMemcache:31 - MemcachedClient.get(com.freewebsys.demo.pojo.UserInfo:0:379)
Hibernate: select userinfo0_.id as id0_0_, userinfo0_.city as city0_0_, userinfo0_.content as content0_0_, userinfo0_.passwd as passwd0_0_, userinfo0_.user_name as user5_0_0_ from user_info userinfo0_ where userinfo0_.id=?
这个也没有命中。也查询下数据库
17:47:58,413 DEBUG HashCodeKeyStrategy:12 - Transformed key [com.freewebsys.demo.pojo.UserInfo#379] to hashCode [379]
17:47:58,413 DEBUG HashCodeKeyStrategy:41 - Final cache key: [com.freewebsys.demo.pojo.UserInfo:0:379]
17:47:58,413 DEBUG MemcachedCache:115 - Memcache.get(com.freewebsys.demo.pojo.UserInfo:0:379)
17:47:58,413 DEBUG SpyMemcache:31 - MemcachedClient.get(com.freewebsys.demo.pojo.UserInfo:0:379)
##################查询结束list size:2
##################第3次查询开始:没有出现查询 数据库请求
17:47:58,416 DEBUG HashCodeKeyStrategy:12 - Transformed key [sql: select userinfo0_.id as id0_, userinfo0_.city as city0_, userinfo0_.content as content0_, userinfo0_.passwd as passwd0_, userinfo0_.user_name as user5_0_ from user_info userinfo0_; parameters: ; named parameters: {}] to hashCode [-129599688]
17:47:58,417 DEBUG HashCodeKeyStrategy:41 - Final cache key: [org.hibernate.cache.StandardQueryCache:0:-129599688]
17:47:58,417 DEBUG MemcachedCache:115 - Memcache.get(org.hibernate.cache.StandardQueryCache:0:-129599688)
17:47:58,417 DEBUG SpyMemcache:31 - MemcachedClient.get(org.hibernate.cache.StandardQueryCache:0:-129599688)
17:47:58,418 DEBUG HashCodeKeyStrategy:12 - Transformed key [user_info] to hashCode [339204258]
17:47:58,418 DEBUG HashCodeKeyStrategy:41 - Final cache key: [org.hibernate.cache.UpdateTimestampsCache:0:339204258]
17:47:58,418 DEBUG MemcachedCache:115 - Memcache.get(org.hibernate.cache.UpdateTimestampsCache:0:339204258)
17:47:58,418 DEBUG SpyMemcache:31 - MemcachedClient.get(org.hibernate.cache.UpdateTimestampsCache:0:339204258)
17:47:58,419 DEBUG HashCodeKeyStrategy:12 - Transformed key [com.freewebsys.demo.pojo.UserInfo#380] to hashCode [380]
17:47:58,419 DEBUG HashCodeKeyStrategy:41 - Final cache key: [com.freewebsys.demo.pojo.UserInfo:0:380]
17:47:58,420 DEBUG MemcachedCache:115 - Memcache.get(com.freewebsys.demo.pojo.UserInfo:0:380)
17:47:58,420 DEBUG SpyMemcache:31 - MemcachedClient.get(com.freewebsys.demo.pojo.UserInfo:0:380)
17:47:58,421 DEBUG HashCodeKeyStrategy:12 - Transformed key [com.freewebsys.demo.pojo.UserInfo#379] to hashCode [379]
17:47:58,422 DEBUG HashCodeKeyStrategy:41 - Final cache key: [com.freewebsys.demo.pojo.UserInfo:0:379]
17:47:58,422 DEBUG MemcachedCache:115 - Memcache.get(com.freewebsys.demo.pojo.UserInfo:0:379)
17:47:58,422 DEBUG SpyMemcache:31 - MemcachedClient.get(com.freewebsys.demo.pojo.UserInfo:0:379)
##################查询结束list size:2
##################第4次查询开始:没有出现查询 数据库请求
17:47:58,425 DEBUG HashCodeKeyStrategy:12 - Transformed key [sql: select userinfo0_.id as id0_, userinfo0_.city as city0_, userinfo0_.content as content0_, userinfo0_.passwd as passwd0_, userinfo0_.user_name as user5_0_ from user_info userinfo0_; parameters: ; named parameters: {}] to hashCode [-129599688]
17:47:58,425 DEBUG HashCodeKeyStrategy:41 - Final cache key: [org.hibernate.cache.StandardQueryCache:0:-129599688]
17:47:58,426 DEBUG MemcachedCache:115 - Memcache.get(org.hibernate.cache.StandardQueryCache:0:-129599688)
17:47:58,426 DEBUG SpyMemcache:31 - MemcachedClient.get(org.hibernate.cache.StandardQueryCache:0:-129599688)
17:47:58,427 DEBUG HashCodeKeyStrategy:12 - Transformed key [user_info] to hashCode [339204258]
17:47:58,427 DEBUG HashCodeKeyStrategy:41 - Final cache key: [org.hibernate.cache.UpdateTimestampsCache:0:339204258]
17:47:58,427 DEBUG MemcachedCache:115 - Memcache.get(org.hibernate.cache.UpdateTimestampsCache:0:339204258)
17:47:58,427 DEBUG SpyMemcache:31 - MemcachedClient.get(org.hibernate.cache.UpdateTimestampsCache:0:339204258)
17:47:58,428 DEBUG HashCodeKeyStrategy:12 - Transformed key [com.freewebsys.demo.pojo.UserInfo#380] to hashCode [380]
17:47:58,428 DEBUG HashCodeKeyStrategy:41 - Final cache key: [com.freewebsys.demo.pojo.UserInfo:0:380]
17:47:58,428 DEBUG MemcachedCache:115 - Memcache.get(com.freewebsys.demo.pojo.UserInfo:0:380)
17:47:58,428 DEBUG SpyMemcache:31 - MemcachedClient.get(com.freewebsys.demo.pojo.UserInfo:0:380)
17:47:58,429 DEBUG HashCodeKeyStrategy:12 - Transformed key [com.freewebsys.demo.pojo.UserInfo#379] to hashCode [379]
17:47:58,429 DEBUG HashCodeKeyStrategy:41 - Final cache key: [com.freewebsys.demo.pojo.UserInfo:0:379]
17:47:58,429 DEBUG MemcachedCache:115 - Memcache.get(com.freewebsys.demo.pojo.UserInfo:0:379)
17:47:58,430 DEBUG SpyMemcache:31 - MemcachedClient.get(com.freewebsys.demo.pojo.UserInfo:0:379)
##################查询结束list size:2
##################第5次查询开始:没有出现查询 数据库请求
17:47:58,433 DEBUG HashCodeKeyStrategy:12 - Transformed key [sql: select userinfo0_.id as id0_, userinfo0_.city as city0_, userinfo0_.content as content0_, userinfo0_.passwd as passwd0_, userinfo0_.user_name as user5_0_ from user_info userinfo0_; parameters: ; named parameters: {}] to hashCode [-129599688]
17:47:58,433 DEBUG HashCodeKeyStrategy:41 - Final cache key: [org.hibernate.cache.StandardQueryCache:0:-129599688]
17:47:58,433 DEBUG MemcachedCache:115 - Memcache.get(org.hibernate.cache.StandardQueryCache:0:-129599688)
17:47:58,433 DEBUG SpyMemcache:31 - MemcachedClient.get(org.hibernate.cache.StandardQueryCache:0:-129599688)
17:47:58,434 DEBUG HashCodeKeyStrategy:12 - Transformed key [user_info] to hashCode [339204258]
17:47:58,434 DEBUG HashCodeKeyStrategy:41 - Final cache key: [org.hibernate.cache.UpdateTimestampsCache:0:339204258]
17:47:58,434 DEBUG MemcachedCache:115 - Memcache.get(org.hibernate.cache.UpdateTimestampsCache:0:339204258)
17:47:58,434 DEBUG SpyMemcache:31 - MemcachedClient.get(org.hibernate.cache.UpdateTimestampsCache:0:339204258)
17:47:58,435 DEBUG HashCodeKeyStrategy:12 - Transformed key [com.freewebsys.demo.pojo.UserInfo#380] to hashCode [380]
17:47:58,435 DEBUG HashCodeKeyStrategy:41 - Final cache key: [com.freewebsys.demo.pojo.UserInfo:0:380]
17:47:58,435 DEBUG MemcachedCache:115 - Memcache.get(com.freewebsys.demo.pojo.UserInfo:0:380)
17:47:58,435 DEBUG SpyMemcache:31 - MemcachedClient.get(com.freewebsys.demo.pojo.UserInfo:0:380)
17:47:58,437 DEBUG HashCodeKeyStrategy:12 - Transformed key [com.freewebsys.demo.pojo.UserInfo#379] to hashCode [379]
17:47:58,437 DEBUG HashCodeKeyStrategy:41 - Final cache key: [com.freewebsys.demo.pojo.UserInfo:0:379]
17:47:58,437 DEBUG MemcachedCache:115 - Memcache.get(com.freewebsys.demo.pojo.UserInfo:0:379)
17:47:58,437 DEBUG SpyMemcache:31 - MemcachedClient.get(com.freewebsys.demo.pojo.UserInfo:0:379)
##################查询结束list size:2
然后在看下 memcache 日志:
可以看出 在第 1,2 次获得数据都是失败的。都要查询下数据库。以后就可以从缓存取得数据了。
17:47:58,433 DEBUG HashCodeKeyStrategy:12 - Transformed key [sql: select userinfo0_.id as id0_, userinfo0_.city as city0_, userinfo0_.content as content0_, userinfo0_.passwd as passwd0_, userinfo0_.user_name as user5_0_ from user_info userinfo0_; parameters: ; named parameters: {}] to hashCode [-129599688]
这个说明 hibernate 对 sql 和参数进行格式化。然后分配下 key。进行缓存。如果是复杂查询每次参数都变化。
其实不适合做缓存。
[root@localhost ~]# echo stats | nc 127.0.0.1 11211
STAT pid 3594
STAT uptime 42
STAT time 1322549632
STAT version 1.4.4
STAT pointer_size 64
STAT rusage_user 0.002999
STAT rusage_system 0.002999
STAT curr_connections 11
STAT total_connections 13
STAT connection_structures 12
STAT cmd_get 21 5次查询 × 2条数据 +第一次初始化?也有可能是查询 formate的sql
STAT cmd_set 3 2条数据 进行set ,+ 有可能是将 fromate的sql 的 hashcode set下。
STAT cmd_flush 0
STAT get_hits 14
STAT get_misses 7
STAT delete_misses 0
STAT delete_hits 0
STAT incr_misses 0
STAT incr_hits 0
STAT decr_misses 0
STAT decr_hits 0
STAT cas_misses 0
STAT cas_hits 0
STAT cas_badval 0
STAT auth_cmds 0
STAT auth_errors 0
STAT bytes_read 2520
STAT bytes_written 7869
STAT limit_maxbytes 67108864
STAT accepting_conns 1
STAT listen_disabled_num 0
STAT threads 4
STAT conn_yields 0
STAT bytes 1594
STAT curr_items 3
STAT total_items 3
STAT evictions 0
END
对于 hibernate search 添加二级 缓存的话 需要增加代码:
QueryParser parser = new QueryParser(Version.LUCENE_31, "content", new SimpleAnalyzer(Version.LUCENE_31)); org.apache.lucene.search.Query luceneQuery = null; try { luceneQuery = parser.parse(content); } catch (ParseException e) { e.printStackTrace(); } FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery( luceneQuery, UserInfo.class); // add second level cache. fullTextQuery.initializeObjectsWith( ObjectLookupMethod.SECOND_LEVEL_CACHE, DatabaseRetrievalMethod.FIND_BY_ID); List<UserInfo> useList = (List<UserInfo>) fullTextQuery.list();
fullTextQuery.initializeObjectsWith(
ObjectLookupMethod.SECOND_LEVEL_CACHE,
DatabaseRetrievalMethod.FIND_BY_ID);
使用DatabaseRetrievalMethod.QUERY 的查询报错。如下所以用的FIND_BY_ID
java.lang.UnsupportedOperationException at com.googlecode.hibernate.memcached.MemcachedCache.toMap(MemcachedCache.java:227) at org.hibernate.cache.impl.bridge.BaseRegionAdapter.contains(BaseRegionAdapter.java:62) at org.hibernate.impl.SessionFactoryImpl$CacheImpl.containsEntity(SessionFactoryImpl.java:982) at org.hibernate.impl.SessionFactoryImpl$CacheImpl.containsEntity(SessionFactoryImpl.java:977) at org.hibernate.search.query.hibernate.impl.SecondLevelCacheObjectsInitializer.initializeObjects(SecondLevelCacheObjectsInitializer.java:65) at org.hibernate.search.query.hibernate.impl.PersistenceContextObjectsInitializer.initializeObjects(PersistenceContextObjectsInitializer.java:81) at org.hibernate.search.query.hibernate.impl.QueryLoader.executeLoad(QueryLoader.java:84) at org.hibernate.search.query.hibernate.impl.AbstractLoader.load(AbstractLoader.java:72) at org.hibernate.search.query.hibernate.impl.FullTextQueryImpl.list(FullTextQueryImpl.java:208) at com.freewebsys.demo.service.impl.UserInfoServiceImpl.findUserInfoBySearchContent(UserInfoServiceImpl.java:83) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) at $Proxy22.findUserInfoBySearchContent(Unknown Source) at com.freewebsys.demo.hibernate_search.AppTest.testSearch(AppTest.java:94) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28) at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
这个定义了 使用 hibernate search 查询的时候 的数据 全部 按照id 到数据库查询。
如果有没有缓存就 先 按照id 进行查询。然后set 到缓存。如果有直接去。
这个运行的非常清晰。
执行多次相同查询的时候。
第一次 执行 了 N 次数据库查询。以后就都没有数据查询了。
总结:
hibernate memcached 缓存配置成功。缓存的调用在第 1 次还是要查询数据的。
并且查询缓存对 是将 sql 和参数 转换成一个 hash 然后进行匹配的。
而在 hibernate search 中的使用 memcached 就是get 形式的查询了。要执行N次。
使用用query 的查询报错。
这样基本满足了对文章搜索的时候 使用缓存 查询的要求了。
在上线的时候 千万要修改下 memcached 的配置
/etc/sysconfig/memcached
ORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="1024"#设置下缓存大小。默认 64
OPTIONS=""
附件是工程代码。