Spring+Xmemcached 使用.

Xmemcache---java 連接memcached緩存服務器的客戶端.

這裏其實可以不用spring來粘合.但是使用spring來配置屬性也是可以的.

那就是寫一個單例工廠類,而參數則可以在spring的xml配置文件中單獨配置.

在通過spring的 factoryBean來產生所需要的bean.

在使用這個bean注入到需要使用的MemcachedClient接口.就可以實現緩存的讀寫.

第一步,創建產生xclient的factoryBean.

package com.xmemcached;

import java.io.IOException;

import com.google.code.yanf4j.config.Configuration;

import net.rubyeye.xmemcached.CommandFactory;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.MemcachedSessionLocator;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.command.BinaryCommandFactory;
import net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator;
import net.rubyeye.xmemcached.utils.AddrUtil;

public class XMemcachedClientFactoryBean {

	private MemcachedClient client;
	// 這裏定義需要配置的參數,然後在使用spring的xml時候進行覆蓋.達到定製客戶端的目的
	private String servers;
	private long timeout = 2000L;
	private CommandFactory commandFactory = new BinaryCommandFactory();
	private Configuration configuration = XMemcachedClientBuilder.getDefaultConfiguration();
	private MemcachedSessionLocator sessionLocator = new KetamaMemcachedSessionLocator();

	public void init() throws Exception {

		if (client == null) {
			synchronized (client) {
				if (client == null) {
					client = createClient();
				}
			}
		}
	}

	// 創建客戶端
	private MemcachedClient createClient() throws IOException {

		// 這裏加載已經配置好的成員變量,返回定製的客戶端.
		MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(servers));
		builder.setCommandFactory(commandFactory);
		// 配置
		builder.setConfiguration(configuration);
		// 連接池
		builder.setConnectionPoolSize(10);
		// 會話
		builder.setSessionLocator(sessionLocator);
		// 對於重新癒合的session,把其重新加到可用隊列中
		builder.setEnableHealSession(true);
		// 10s連接
		builder.setConnectTimeout(10000L);
		// 這裏不使用失敗模式,在節點請求失敗後,可以迅速把此節點剔除,從而使用另外的節點
		builder.setFailureMode(false);
		MemcachedClient xClient = builder.build();
		xClient.setOpTimeout(timeout);
		return xClient;
	}

	//這個方法用於生成對應的bean.
	public MemcachedClient getClient() {
		return client;
	}

	public void setClient(MemcachedClient client) {
		this.client = client;
	}

	public String getServers() {
		return servers;
	}

	public void setServers(String servers) {
		this.servers = servers;
	}

	public long getTimeout() {
		return timeout;
	}

	public void setTimeout(long timeout) {
		this.timeout = timeout;
	}

	public CommandFactory getCommandFactory() {
		return commandFactory;
	}

	public void setCommandFactory(CommandFactory commandFactory) {
		this.commandFactory = commandFactory;
	}

	public Configuration getConfiguration() {
		return configuration;
	}

	public void setConfiguration(Configuration configuration) {
		this.configuration = configuration;
	}

	public MemcachedSessionLocator getSessionLocator() {
		return sessionLocator;
	}

	public void setSessionLocator(MemcachedSessionLocator sessionLocator) {
		this.sessionLocator = sessionLocator;
	}

}

第二步:配置注入的參數,產生bean.

<?xml version="1.0" encoding="UTF-8"?>
<beans default-autowire="byName" 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.xsd">

	<description>spring-context加載xmemcached配置</description>



	<bean name="xmemFactoryBean" class="com.xmemcached.XMemcachedClientFactoryBean" init-method="init" destroy-method="destroy">
		<!-- 屬性注入 -->
		<property name="servers" value="localhost:123456" />
		<property name="timeout" value="5000"></property>
		<property name="sessionLocator">
			<bean class="net.rubyeye.xmemcached.impl.KetamaMemcachedSessionLocator" />
		</property>
	</bean>
	<!-- 產生的bean -->
	<bean name="myClient" factory-bean="xmemFactoryBean" factory-method="getClient" />

</beans>

第三步,寫測試類.

package com.xmemcached;

import java.util.concurrent.TimeoutException;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = { "classpath*:context.xml" })
public class XMemcachedTest {

	@Autowired
	@Qualifier("myClient")
	private MemcachedClient client;

	private static final Logger log = LoggerFactory.getLogger(XMemcachedTest.class);

	//測試
	@Test
	public  void test(String[] args) {
		set("hello", 30, "nihao");
		System.out.println(get("hello"));
	}

	// 添加緩存
	public <T> boolean set(final String key, int expireTimeInSecond, final T value) {
		try {
			return client.set(key, expireTimeInSecond, value);
		} catch (TimeoutException e) {
			log.error("{key:'" + key + "',expireTime:'" + expireTimeInSecond + "',value:'" + value + "'}", e);
		} catch (InterruptedException e) {
			log.error("{key:'" + key + "',expireTime:'" + expireTimeInSecond + "',value:'" + value + "'}", e);
		} catch (MemcachedException e) {
			log.error("{key:'" + key + "',expireTime:'" + expireTimeInSecond + "',value:'" + value + "'}", e);
		}
		return false;
	}

	// 獲取緩存
	public <T> T get(String key) {
		try {
			return client.get(key);
		} catch (TimeoutException e) {
			log.error("{key: '" + key + "'}", e);
		} catch (InterruptedException e) {
			log.error("{key: '" + key + "'}", e);
		} catch (MemcachedException e) {
			log.error("{key: '" + key + "'}", e);
		} catch (Throwable e) {
			log.error("{key: '" + key + "'}", e);
		}
		return null;
	}
}

另外,這裏可配置的東西挺多的,可以自定義實現序列化等等.簡單實用的話,可以不用管這些,但是做框架封裝時須要考慮取捨.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章