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;
        	}
    	}
    }

 是不是很简答,就这样就实现了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值