我一直在尝试同样的事情,我想我已经成功了。看看亚马逊的 MemcachedClient的构造函数。您需要将 clientMode 设置为 ClientMode.Static 以连接到普通的 memcached 服务器或 ClientMode.Dynamic 以通过自动发现连接到 ElastiCache。根据您使用的构造函数,您可以传入一个将 clientMode 设置为静态的 ConnectionFactory,或者您可以传入一个不包含“.cfg.”的地址。
我使用的是 Spring,所以我创建了一个扩展 MemcachedClientFactoryBean 的类,以在 connectionFactory 上设置 clientMode。
<bean id="memcachedClient" class="au.com.mycompany.MyMemcachedClientFactoryBean">
<property name="servers" value="${memcached.server}"/>
<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>
这是我的 FactoryBean
package au.com.mycompany;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.ClientMode;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.spring.MemcachedClientFactoryBean;
public class MyMemcachedClientFactoryBean extends MemcachedClientFactoryBean {
private final ConnectionFactoryBuilder connectionFactoryBuilder = new ConnectionFactoryBuilder();
private String servers;
@Override
public Object getObject() throws Exception {
if (servers.contains("127.0.0.1")) {
connectionFactoryBuilder.setClientMode(ClientMode.Static);
} else {
connectionFactoryBuilder.setClientMode(ClientMode.Dynamic);
}
return new MemcachedClient(connectionFactoryBuilder.build(), AddrUtil.getAddresses(servers));
}
@Override
public void setServers(final String newServers) {
this.servers = newServers;
}
}