spy memcache 客户端使用体会

来源:互联网 发布:数据工程师是干嘛的 编辑:程序博客网 时间:2024/06/09 14:30

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

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

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 脸上发红发痒起疙瘩怎么办 脸过敏了怎么办最简单 胸下垂应该怎么办19岁 身上的肉特别松怎么办 才30岁脸部松弛怎么办 脸上的皮肤很松怎么办 面部皮肤干燥起皮刺痛怎么办 脸上的皮肤很粗糙怎么办 脸上又红又痒怎么办 鲜红斑痣增生了怎么办 激光祛斑后色素沉着怎么办 白球鞋洗后发黄怎么办 夏天出汗妆花了怎么办 买的小产权房怎么办 嘴唇起皮怎么办小妙招 照相嘴巴是歪的怎么办 鼻子笑起来很宽怎么办 财运不好怎么办最近你有偏财 从小缺爱的人怎么办 一到晚上就怕死怎么办 碰到不讲理的人怎么办 遇到不讲理的人怎么办 蚰蜓虫子咬了怎么办 腰肌损伤怎么办恢复快 腰闪了怎么办最有效 墨兰严重烂根怎么办 铁兰花变绿了怎么办 1岁半宝宝吵瞌睡怎么办 28天宝宝吵瞌睡怎么办 2个月宝宝闹瞌睡怎么办 被刺猬的刺扎了怎么办 买电脑被坑了怎么办 买电脑被坑了怎么办啊 在电脑城被坑了怎么办 小狗20天不睁眼怎么办 金星秀停播沈南怎么办 干了活拿不到钱怎么办 干完活要不到钱怎么办 让蚊子咬了很痒怎么办 秋天被蚊子咬了怎么办 练芭蕾脚背太硬怎么办