前提条件:在阿里云已购买缓存服务器
1、引入缓存机制需要的jar包: spymemcached-2.11.4.jar
2、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" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="authdescriptor" class="net.spy.memcached.auth.AuthDescriptor">
<constructor-arg index="0">
<array value-type="java.lang.String">
<value>PLAIN</value>
</array>
</constructor-arg>
<constructor-arg index="1" ref="plaincallbackhandler"></constructor-arg>
</bean>
<bean id="plaincallbackhandler" class="net.spy.memcached.auth.PlainCallbackHandler">
<constructor-arg index="0" value="缓存服务器用户名"></constructor-arg>
<constructor-arg index="1" value="缓存服务器密码"></constructor-arg>
</bean>
<bean id="connectionfactorybuilder" class="net.spy.memcached.ConnectionFactoryBuilder"
init-method="build">
<property name="opFact" ref="binaryoperationfactory"></property>
<property name="authDescriptor" ref="authdescriptor"></property>
</bean>
<bean name="connectionfactory" factory-bean="connectionfactorybuilder" factory-method="build"/>
<bean id="binaryoperationfactory"
class="net.spy.memcached.protocol.binary.BinaryOperationFactory">
</bean>
<bean id="asciioperationfactory"
class="net.spy.memcached.protocol.ascii.AsciiOperationFactory">
</bean>
<bean name="addrutil" class="net.spy.memcached.AddrUtil"
factory-method="getAddresses">
<constructor-arg>
<value缓存服务器地址(形式:ip:port)</value>
</constructor-arg>
</bean>
<bean id="memcachedclient" class="net.spy.memcached.MemcachedClient">
<constructor-arg index="0" ref="connectionfactory"></constructor-arg>
<constructor-arg index="1" ref="addrutil"></constructor-arg>
</bean>
</beans>
3、代码调用:
// 新增缓存,key为缓存的key,timeOut为缓存的失效时间,单位为秒,object为缓存value
memcachedClient.set(key, timeOut, object);
// 根据key获取缓存数据
memcachedClient.get(key);
// 清除所有缓存
memcachedClient.flush();
// 删除指定缓存
memcachedClient.delete(key);