-
lpush
從左邊(隊頭)添加數據。 -
rpop
從右邊(隊尾)拉取數據
可以實現阻塞隊列
可以實現固定大小的容器
應用場景案例:Redis用List實現隊列。從左端添加數據,從右端消費數據。
//添加任務
final ScheduledFuture<?> scheduledFuture = SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
//添加任務
redisTemplate.executePipelined(new SessionCallback<Object>() {
@Override
public Object execute(RedisOperations operations) throws DataAccessException {
for (int i = 0; i < 2000; i++) {
operations.opsForList().leftPush(SCHEDULE_TASK_PREFIX, "task:" + atomicInteger.incrementAndGet());
}
return null;
}
});
}
}, 0, 2, TimeUnit.SECONDS);
消費任務
for (int i = 0; i < 10; i++) {
SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
//消費任務
List<Object> objects = redisTemplate.executePipelined(new SessionCallback<Object>() {
@Override
public Object execute(RedisOperations operations) throws DataAccessException {
for (int i = 0; i < 100; i++) {
operations.opsForList().rightPop(SCHEDULE_TASK_PREFIX);
}
return null;
}
});
}
}, 0, 1, TimeUnit.SECONDS);
}
主線程監聽隊列
while (true) {
Thread.sleep(5000);
if (atomicInteger.get() > 100000) {
scheduledFuture.cancel(true);
}
System.out.println("當前任務數:" + redisTemplate.opsForList().size(SCHEDULE_TASK_PREFIX));
}
基於list的延遲隊列設計方案
說明:
- 主要用到了list類型中阻塞相關的命令。