快速實用-消息隊列之Redis簡易實現 Demo

Redis消息隊列

同學們是否有過類似開發過程中的糾結?

  • 項目太小,不想引入MQ,但又想實現異步任務?
  • 初來乍到只會用Redis,MQ暫時不懂,還要學習,不太會用,就想怎麼簡單怎麼來。
  • 分佈式下,就想把日誌統一收集起來,寫在某個地方。

那麼Redis就可以做到,實現一個超級簡單的消息隊列。

當然第一種情況,單機版的@Async就可以了,也不需要MQ和Redis

廢話不多說,直接上碼:

消費:

配合CommandLineRunner 直接實現開機監聽

blpop是redis的阻塞函數,也就是說沒有消息,就一直等待。

@Component
public class StartupRunner implements CommandLineRunner {
 private Logger logger = LoggerFactory.getLogger(this.getClass());
 @Autowired
 private RedisUtil redisUtil;
 @Override
 public void run(String... args) throws Exception {
 logger.info("**************Application startup successful*************");
 while (true){
 String message= redisUtil.blpop("queueMessage");
 logger.info("收到了隊列:{},的消息:{}","queueMessage",message);
 }
 }
}

生產隊列消息:

lpush

@ApiOperation(value = "消息發送")
@RequestMapping(value = "/pushMessage", method = RequestMethod.POST)
public GeneralResponseDto pushMessage(@RequestParam("message") String message) throws IOException {
 redisUtil.lpush("queueMessage",message);
 return GeneralResponseDto.addSuccess("發送成功", message);
}
 

測試:

快速實用-消息隊列之Redis簡易實現 Demo

發送了2次請求,寫入了2次

同學們有靈感了嗎,某些場景還是很方便的哦。


分享到:


相關文章: