萌生出这样的想法,主要是工作中暂时没有引进任何的消息队列,但是实际的开发中,却有这样的场景且比较紧急处理,因此借鉴了网上的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的溢出问题。