当前位置: 首页 > 工具软件 > Spymemcached > 使用案例 >

spymemcached集成

谢典
2023-12-01

1:

官方地址:https://code.google.com/p/spymemcached/downloads/list

2:放入https://spymemcached.googlecode.com/files/spymemcached-2.9.1.jar 到lib目录下

3:加入spring配置文件applicationContext-spymemcached.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"
	default-lazy-init="true">
	<description>spymemcached 缓存配置(集中分布式缓存系统 memcached)</description>

	<bean id="spymemcachedClient" class="net.spy.memcached.spring.MemcachedClientFactoryBean">
		<property name="servers" value="${memcache.spymemcacheServers}" />
		<property name="protocol" value="BINARY" />
		<property name="transcoder">
			<bean class="net.spy.memcached.transcoders.SerializingTranscoder">
				<property name="compressionThreshold" value="1024" />
			</bean>
		</property>
		<property name="opTimeout" value="1000" />
		<property name="timeoutExceptionThreshold" value="1998" />
		<property name="hashAlg">
			<value type="net.spy.memcached.DefaultHashAlgorithm">KETAMA_HASH</value>
		</property>
		<property name="locatorType" value="CONSISTENT" />
		<property name="failureMode" value="Redistribute" />
		<property name="useNagleAlgorithm" value="false" />
	</bean> 

</beans>

 4:加入属性文件配置:

# spymemcached client
memcache.spymemcacheServers=192.168.6.253:11311,192.168.6.143:11411

 5:单元测试:

package com.capitalbio.soft.test.memcached.spymemcached;

import net.spy.memcached.MemcachedClient;
import net.spy.memcached.internal.OperationFuture;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;

import com.capitalbio.soft.core.utils.spring.SpringContextHolder;
import com.capitalbio.soft.test.core.SpringTransactionalTestCase;

@ContextConfiguration(locations = { "/applicationContext.xml", "/applicationContext-spymemcached.xml" })
public class SpyMemcachedTest extends SpringTransactionalTestCase {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Test
	public void testMemcached() {
		try {
			MemcachedClient client = SpringContextHolder.getBean(MemcachedClient.class);
			// Store a value (async) for one hour
			client.set("someKey", 3600, "中文值!");
			// replace the value
			client.replace("someKey", 33, "另一个值!");
			// Retrieve a value.
			Object ret = client.get("someKey");
			OperationFuture<Boolean> retb = client.delete("someKey");
			logger.debug("{}:{}",ret,retb.get());
		} catch (Exception e) {
			logger.error("", e);
		}
	}

}

 6:高级示例:

https://code.google.com/p/spymemcached/wiki/Examples

7:原型单元测试,且将spring配置文件加入到spring总配置中,即可使用!

 类似资料: