Redis--List

  • lpush
    從左邊(隊頭)添加數據。

  • rpop
    從右邊(隊尾)拉取數據

lpush+rpop\color{#FF0000}{ lpush+rpop可以實現隊列。}
lpush+lpop\color{#FF0000}{ lpush+lpop可以實現棧的功能。}
lpush+brpop\color{#FF0000}{lpush+brpop}可以實現阻塞隊列
lpush+ltrim\color{#FF0000}{lpush+ltrim}可以實現固定大小的容器

應用場景案例: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類型中阻塞相關的命令。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章