Memcache模拟队列实现

        萌生出这样的想法,主要是工作中暂时没有引进任何的消息队列,但是实际的开发中,却有这样的场景且比较紧急处理,因此借鉴了网上的php实例,用java模拟了消息队列的实现,push为主动调取,pop为quarters 定时处理。废话不多说,直接上代码:

/**
 * queue push
 *
 * @param value
 * @param queue
 * @param <T>
 * @author chengjinqi
 */
public static <T> void push(T value, String queue) {
    if (value == null) {
        return;
    }

    StringBuffer pushedCountKey = new StringBuffer("Queue:").append(queue).append(":PushedCount"); //入队数量key
    Integer pushedCount = 0;
    T count = MemCache.getCache(pushedCountKey.toString());
    if (count != null) {
        pushedCount = (Integer) count;
    }

    logger.debug("push count: " + pushedCount);

    //push
    StringBuffer queueDataKey = new StringBuffer("Queue:").append(queue).append(":Data:").append(pushedCount); //队列数据
    logger.debug("push data key: " + queueDataKey.toString());
    MemCache.buildCacheWithMinute(queueDataKey.toString(), value, 10);

    //累计已压进元素个数
    if (pushedCount > 0) {
        pushedCount++;
    } else {
        pushedCount = 1;
    }
    MemCache.buildCacheWithMinute(pushedCountKey.toString(), pushedCount, 0);
}

/**
 * queue pop
 *
 * @param queue
 * @param <T>
 * @return <T> value
 * @author chengjinqi
 */
public static <T> T pop(String queue) {

    StringBuffer popedCountKey = new StringBuffer("Queue:").append(queue).append(":PopedCount"); //出队数量key

    Integer popedCount = 0;
    T count = MemCache.getCache(popedCountKey.toString());
    if (count != null) {
        popedCount = (Integer) count;
    }

    logger.debug("pop count: " + popedCount);

    //pop
    StringBuffer queueDataKey = new StringBuffer("Queue:").append(queue).append(":Data:").append(popedCount); //队列数据
    logger.debug("pop data key: " + queueDataKey.toString());
    T value = MemCache.getCache(queueDataKey.toString());
    if (value != null) {
        //从队列中删除此数据
        MemCache.DeleteCache(queueDataKey.toString());

        //累计弹出元素个数
        if (popedCount > 0) {
            popedCount++;
        } else {
            popedCount = 1;
        }
        MemCache.buildCacheWithMinute(popedCountKey.toString(), popedCount, 0);
    }

    return value;
}


比较需要注意的是,Integer的溢出问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值