SpringBoot——redis消息队列list(二十二)

前言

redis的lpush和rpop很适合作为一种轻量级的消息队列实现,这与redis的list列表有关,详情见

生产者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Service
public class RedisProducerImpl implements RedisProducer {

@Autowired
private RedisTemplate redisTemplate;

@Override
public JsonResponse produce(String key, String msg) {
Map<String, String> map = Maps.newHashMap();
map.put("fileId", msg);
redisTemplate.opsForList().leftPush(key, map);
return JsonResponse.ok();
}
}

消费者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Service
public class RedisConsumer {

private void processOrderImport() {
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> {
while (true) {
Object object = redisTemplate.opsForList().rightPop(RedisKey.orderImportKey, 1, TimeUnit.SECONDS);
if (null == object) {
continue;
}
String msg = JSON.toJSONString(object);
executorService.execute(*******);
}
});
}
}
文章目录
  1. 1. 前言
  2. 2. 生产者
  3. 3. 消费者
|