`
marc
  • 浏览: 17245 次
社区版块
存档分类
最新评论

memcached的使用(二)hibernate cache provider

阅读更多
实现hibernate的cache provider,让hibernate使用memcached缓存。
这里比较简单,由于memcached的SockIOPool已经在(一)中spring中初始化了,这里就不考虑pool的初始化,直接获得MemCachedClient使用即可。
然后配置给hibernate<prop key="hibernate.cache.provider_class">×××</prop>

附代码:
/**
 * @author Marc
 *
 */
public class MemcachedProvider implements CacheProvider {
	public Cache buildCache(String name, Properties properties) throws CacheException {
		return new MemCache(name);
	}

	public boolean isMinimalPutsEnabledByDefault() {
		return false;
	}

	public long nextTimestamp() {
		return Timestamper.next();
	}

	public void start(Properties properties) throws CacheException {
	}

	public void stop() {
	}

}

/**
 * @author Marc
 * 
 */
public class MemCache implements Cache {
	private static final Log log = LogFactory.getLog(MemCache.class);

	private static final int SIXTY_THOUSAND_MS = 60000;

	MemCachedClient mc;
	String regionName;

	/**
	 * Creates a new Hibernate pluggable cache based on a cache name. <p/>
	 * 
	 * @param cache
	 *            The underlying EhCache instance to use.
	 */
	public MemCache(String regionName) {
		mc = new MemCachedClient();
		mc.setCompressEnable(false);
		this.regionName = regionName;
	}

	/**
	 * Gets a value of an element which matches the given key.
	 * 
	 * @param key
	 *            the key of the element to return.
	 * @return The value placed into the cache with an earlier put, or null if
	 *         not found or expired
	 * @throws CacheException
	 */
	public Object get(Object key) throws CacheException {
		if (log.isDebugEnabled()) {
			log.debug("key: " + key);
		}
		if (key == null) {
			return null;
		} else {
			Object rt = mc.get(key.toString());
			if (rt == null) {
				if (log.isDebugEnabled()) {
					log.debug("Element for " + key + " is null");
				}
				return null;
			} else {
				return rt;
			}
		}

	}

	public Object read(Object key) throws CacheException {
		return get(key);
	}

	/**
	 * Puts an object into the cache.
	 * 
	 * @param key
	 *            a key
	 * @param value
	 *            a value
	 * @throws CacheException
	 *             if the {@link CacheManager} is shutdown or another
	 *             {@link Exception} occurs.
	 */
	public void update(Object key, Object value) throws CacheException {
		put(key, value);
	}

	/**
	 * Puts an object into the cache.
	 * 
	 * @param key
	 *            a key
	 * @param value
	 *            a value
	 * @throws CacheException
	 *             if the {@link CacheManager} is shutdown or another
	 *             {@link Exception} occurs.
	 */
	public void put(Object key, Object value) throws CacheException {
		mc.set(key.toString(), value);
	}

	/**
	 * Removes the element which matches the key. <p/> If no element matches,
	 * nothing is removed and no Exception is thrown.
	 * 
	 * @param key
	 *            the key of the element to remove
	 * @throws CacheException
	 */
	public void remove(Object key) throws CacheException {
		mc.delete(key.toString());
	}

	/**
	 * Remove all elements in the cache, but leave the cache in a useable state.
	 * 
	 * @throws CacheException
	 */
	public void clear() throws CacheException {
		log.warn("cann't clear all items in memcached!");
		throw new CacheException("cann't clear all items in memcached!");
	}

	/**
	 * Remove the cache and make it unuseable.
	 * 
	 * @throws CacheException
	 */
	public void destroy() throws CacheException {

	}

	/**
	 * Calls to this method should perform there own synchronization. It is
	 * provided for distributed caches. Because EHCache is not distributed this
	 * method does nothing.
	 */
	public void lock(Object key) throws CacheException {
	}

	/**
	 * Calls to this method should perform there own synchronization. It is
	 * provided for distributed caches. Because EHCache is not distributed this
	 * method does nothing.
	 */
	public void unlock(Object key) throws CacheException {
	}

	/**
	 * Gets the next timestamp;
	 */
	public long nextTimestamp() {
		return Timestamper.next();
	}

	/**
	 * Returns the lock timeout for this cache.
	 */
	public int getTimeout() {
		// 60 second lock timeout
		return Timestamper.ONE_MS * SIXTY_THOUSAND_MS;
	}

	public String getRegionName() {
		return this.regionName;
	}

	/**
	 * Warning: This method can be very expensive to run. Allow approximately 1
	 * second per 1MB of entries. Running this method could create liveness
	 * problems because the object lock is held for a long period <p/>
	 * 
	 * @return the approximate size of memory ehcache is using for the
	 *         MemoryStore for this cache
	 */
	public long getSizeInMemory() {
		log.warn("cann't getSizeInMemory in memcached!");
		throw new CacheException("cann't getSizeInMemory in memcached!");
	}

	public long getElementCountInMemory() {
		log.warn("cann't getElementCountInMemory in memcached!");
		throw new CacheException("cann't getElementCountInMemory in memcached!");
	}

	public long getElementCountOnDisk() {
		log.warn("cann't getElementCountOnDisk in memcached!");
		throw new CacheException("cann't getElementCountOnDisk in memcached!");
	}

	public Map toMap() {
		log.warn("cann't toMap in memcached!");
		throw new CacheException("cann't toMap in memcached!");
	}

	public String toString() {
		return "MemCached(" + getRegionName() + ')';
	}

}
分享到:
评论
6 楼 hqman 2007-07-31  
求助高手!!!!!!!!!!1

我在memcached client端 把key 打印出来 值 居然是 对应model 的数据库表名,而不是期望的 id。
5 楼 lanhuai 2007-01-19  
请高手来鉴定一下我的方法是否有问题??
4 楼 lanhuai 2007-01-19  
把这个encodeKey返回的结果传给MemCachedClient 的方法,就可以了
3 楼 lanhuai 2007-01-19  
主要是有几个方法的Object key这个参数的使用问题。

做查询的时候,hibernate会将整个sql做为key,其中有空格(还有一些其他的字符,想不起来了)等等,会导致memcached出错。

所以,要取key的hashCode才行。但是为了避免某些字符串的hashCode相同,我是这样做的。


    
/**
     * 取key的hashCode做为memcached的key,避免key中的一些特殊符号导致memcached工作异常
     * @param key
     * @return hashCode后的key
     */
    private String encodeKey(Object key) {
        int hashCode = new HashCodeBuilder(-167198555, -754611037).append(String.valueOf(key)).append(getRegionName()).toHashCode();
        return String.valueOf(hashCode);
    }
2 楼 lanhuai 2006-11-01  
这个cache provider有问题,如果楼主遇到了,并且解决了,那我就先不发解决方法了
1 楼 wolfsquare 2006-10-19  
老兄您要挣分也别这样挣好不.

相关推荐

    hibernate4.0使用二级缓存jar包

    ehcache 二级缓存 配置使用的jar包 配置如下: &lt;!-- 启用二级缓存 --&gt; &lt;property name="hibernate.cache.use_second_level_cache"&gt;true &lt;!-- 查询的二级缓存配置 --&gt; &lt;property name="hibernate....

    hibernate-memcached包

    这通常涉及修改Hibernate的配置文件,添加相关的provider和cache regions。同时,还需要在应用环境中部署并配置Memcached服务器,以供Hibernate连接和存储数据。一旦配置完成,Hibernate会在适当的时候自动将数据...

    hibernate整合memcached需要的jar包

    2. **配置Hibernate**:在Hibernate的配置文件(通常是`hibernate.cfg.xml`)中,设置`cache.provider_class`属性为`net.sf.hibernate.cache.MemcachedCacheProvider`,并配置Memcached服务器的地址和端口。...

    memcached在SSH中的配置

    - 如果项目使用Hibernate,可以集成Ehcache或第三方memcached实现(如hibernate-ehcache-memcached),配置hibernate.cfg.xml或使用XML/Annotation方式定义缓存策略。 5. **使用示例**: - 在服务端,可以通过...

    hibernate配置二三级缓存

    &lt;property name="hibernate.cache.provider_class"&gt;org.hibernate.cache.EhCacheProvider &lt;!-- 其他缓存配置 --&gt; &lt;/hibernate-configuration&gt; ``` **4. 映射文件中启用缓存** 在实体类对应的`.hbm.xml`映射...

    Nhibernate2.2 配置模版

    例如,可以使用第三方缓存提供商如Memcached或Redis,通过`cache`元素设定缓存策略。 4. **查询语言配置**:Nhibernate支持HQL(Hibernate Query Language)和 Criteria 查询,可以在配置文件中定义默认的查询语言...

    javaweb项目常用jar包

    simple-spring-memcached-3.5.0.jar slf4j-api-1.6.0.jar slf4j-log4j12-1.6.0.jar solr-solrj-3.4.0.jar spring-aop-4.1.6.RELEASE.jar spring-aspects-4.1.6.RELEASE.jar spring-beans-4.1.6.RELEASE.jar ...

    java开源包8

    支持使用Redis和Memcached作为后端缓存。3. 支持缓存数据分区规则的定义 4. 使用redis作缓存时,支持list类型的高级数据结构,更适合论坛帖子列表这种类型的数据 5. 支持混合使用redis缓存和memcached缓存。可以将...

    java开源包1

    支持使用Redis和Memcached作为后端缓存。3. 支持缓存数据分区规则的定义 4. 使用redis作缓存时,支持list类型的高级数据结构,更适合论坛帖子列表这种类型的数据 5. 支持混合使用redis缓存和memcached缓存。可以将...

    java开源包11

    支持使用Redis和Memcached作为后端缓存。3. 支持缓存数据分区规则的定义 4. 使用redis作缓存时,支持list类型的高级数据结构,更适合论坛帖子列表这种类型的数据 5. 支持混合使用redis缓存和memcached缓存。可以将...

    java开源包2

    支持使用Redis和Memcached作为后端缓存。3. 支持缓存数据分区规则的定义 4. 使用redis作缓存时,支持list类型的高级数据结构,更适合论坛帖子列表这种类型的数据 5. 支持混合使用redis缓存和memcached缓存。可以将...

    java开源包3

    支持使用Redis和Memcached作为后端缓存。3. 支持缓存数据分区规则的定义 4. 使用redis作缓存时,支持list类型的高级数据结构,更适合论坛帖子列表这种类型的数据 5. 支持混合使用redis缓存和memcached缓存。可以将...

    java开源包6

    支持使用Redis和Memcached作为后端缓存。3. 支持缓存数据分区规则的定义 4. 使用redis作缓存时,支持list类型的高级数据结构,更适合论坛帖子列表这种类型的数据 5. 支持混合使用redis缓存和memcached缓存。可以将...

    java开源包5

    支持使用Redis和Memcached作为后端缓存。3. 支持缓存数据分区规则的定义 4. 使用redis作缓存时,支持list类型的高级数据结构,更适合论坛帖子列表这种类型的数据 5. 支持混合使用redis缓存和memcached缓存。可以将...

    java开源包10

    支持使用Redis和Memcached作为后端缓存。3. 支持缓存数据分区规则的定义 4. 使用redis作缓存时,支持list类型的高级数据结构,更适合论坛帖子列表这种类型的数据 5. 支持混合使用redis缓存和memcached缓存。可以将...

    java开源包4

    支持使用Redis和Memcached作为后端缓存。3. 支持缓存数据分区规则的定义 4. 使用redis作缓存时,支持list类型的高级数据结构,更适合论坛帖子列表这种类型的数据 5. 支持混合使用redis缓存和memcached缓存。可以将...

    java开源包7

    支持使用Redis和Memcached作为后端缓存。3. 支持缓存数据分区规则的定义 4. 使用redis作缓存时,支持list类型的高级数据结构,更适合论坛帖子列表这种类型的数据 5. 支持混合使用redis缓存和memcached缓存。可以将...

    java开源包9

    支持使用Redis和Memcached作为后端缓存。3. 支持缓存数据分区规则的定义 4. 使用redis作缓存时,支持list类型的高级数据结构,更适合论坛帖子列表这种类型的数据 5. 支持混合使用redis缓存和memcached缓存。可以将...

    java开源包101

    支持使用Redis和Memcached作为后端缓存。3. 支持缓存数据分区规则的定义 4. 使用redis作缓存时,支持list类型的高级数据结构,更适合论坛帖子列表这种类型的数据 5. 支持混合使用redis缓存和memcached缓存。可以将...

Global site tag (gtag.js) - Google Analytics