1. 程式人生 > >spy memcache 客戶端使用體會

spy memcache 客戶端使用體會

incr 和desc 方法法引入

       專案中需要使用到一個計數的功能,而且是在指定的時間段內某事物的使用的次數。經過查詢使用到了memcache的incr 和desc方法。該功能很好用,分享給大家。以下是官網對該方法的描述:
       Memcached的incr 和 decr命令用於增加現有鍵的數值遞減。如果鍵未找到或如果關鍵的不是數字,則返回NOT_FOUND。那麼CLIENT_ERROR不能增加或返回遞減非數值錯誤。

     incr/decr有很多過載方法,我使用的是如下這個:   

<span style="font-family:KaiTi_GB2312;font-size:18px;">/**
* key不做介紹,by 是要增加或或者減少的步長,defaultValue:當根據key值沒有找到時,key值得預設value;expire:過期時間,秒為單位
*/
memcachedClient.incr/decr(key, by, defaultValue,expiry);</span>
方法很簡單,這裡我們順便說說客戶單memcache的使用。

memcache使用

       1、引用

     因為我們是maven專案,所以只需要在pom檔案中新增

<dependency>
            <groupId>net.spy</groupId>
            <artifactId>spymemcached</artifactId>
            <version>2.11.6</version>
        </dependency>
同樣,我們是寫了一個訪問memcache的工具類,而並非直接訪問,這樣解耦靈活,不必多說。
        在工具類中,我們定義了一個帶引數構造方法,將mencache的例項通過外部傳入,當然不是在呼叫方傳入,這樣和在工具類中無兩樣,都是硬編碼,我們把具體的執行例項寫在了配置檔案中,通過系統系統,注入進來,這樣的好處是,以後我們換memcache服務容易。配置改變即可,先來看看配置吧:

       2、配置檔案
             在配置檔案中把memcache的伺服器,埠號,操作過期時間,容器等資訊。這是一個配置好Bean。

<bean id="memcachedClient" class="net.spy.memcached.spring.MemcachedClientFactoryBean">
		<property name="servers" value="cache.ufenqi.biz:11211" />
		<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="1800" />
		<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>
	<bean id="cacheClient" class="com.bjmd.cache.impl.BaJieMemcachedClient">
		<property name="memcachedClient" ref="memcachedClient" />
	</bean>
             3、工具類
public class xmMemcachedClient implements CacheClient {
    private MemcachedClient memcachedClient;
    public void setMemcachedClient(MemcachedClient memcachedClient) {
        this.memcachedClient = memcachedClient;
    }
    /**
     * 設定快取資料
     * @param key   鍵
     * @param value 值
     * @param expiry    有效期
     */
    public Boolean set(String key, Object value, int expiry) {
        if (StringUtils.isEmpty(key) || value == null) {
            return false;
        }
        try{
            OperationFuture<Boolean> operationFuture = memcachedClient.set(key, expiry * 60, value);
            return operationFuture.get();
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 獲取快取資料
     * @param key
     * @return
     */
    public Object get(String key) {
        if (StringUtils.isEmpty(key))
            return Boolean.valueOf(false);
        Object o = null;
        try {
            o = memcachedClient.get(key);
        } catch (OperationTimeoutException e) {
            e.printStackTrace();
        }
        return o;
    }
    /**
     * 刪除快取資料
     * @param key
     */
    public Boolean delete(String key) {
        if (StringUtils.isEmpty(key)) {
            return false;
        }
        try{
            OperationFuture<Boolean> operationFuture = memcachedClient.delete(key);
            return operationFuture.get();
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }
    /**
     * 檢查快取資料是否存在
     * @param key
     * @return
     */
    public boolean exists(String key) {
        if (StringUtils.isEmpty(key))
            return false;
        else
            return memcachedClient.get(key) != null;
    }
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Map getMulti(List keys) {
        if (keys == null || keys.size() == 0) {
            return new HashMap(0);
        } else {
            String strKeys[] = new String[keys.size()];
            strKeys = (String[]) keys.toArray(strKeys);
            return memcachedClient.getBulk(strKeys);
        }
    }
    @SuppressWarnings("rawtypes")
    public Object[] getMulti(String keys[]) {
        if (keys == null || keys.length == 0) {
            return new Object[0];
        } else {
            Map map = memcachedClient.getBulk(keys);
            return map.values().toArray();
        }
    }
    /**
     * Incr方法.
     */
    public long incr(String key, int by, long defaultValue,int expiry) {
        return memcachedClient.incr(key, by, defaultValue,expiry * 60);
    }
    /**
     * Decr方法.
     */
    public long decr(String key, int by, long defaultValue,int expiry) {
        return memcachedClient.decr(key, by, defaultValue,expiry * 60);
    }
}
    4、開始呼叫
@Autowired
  public CacheClient cacheClient;
  /**
     * 判斷緩衝次數,決定是否可以再次訪問
     * @param userId
     * @return
     */
    private boolean getTongdunCount(Long userId){
    	// 先從緩衝中拿值
    	if(!cacheClient.exists(RISK_TONGDUN_PREFIX+userId)){
//    		cacheClient.set(RISK_TONGDUN_PREFIX+userId, 1, 60 *24);
    		return true;
    	}else{
    		long count = cacheClient.incr(RISK_TONGDUN_PREFIX+userId, 1, 1, this.limitUserTongdunExpireTime);
    		if(count > 2){
        		return false;
        	}else{
        		return true;
        	}
    	}
    }

 是不是很簡答,就這樣就實現了。