用redis中的List可以实现队列,这样可以用来做消息处理和任务调度的队列
队列生产者
package cn.stylefeng.guns.knowledge.modular.knowledge.schedule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.Random;
import java.util.UUID;
@Slf4j
public class QueueProducer implements Runnable {
public static final String QUEUE_PRODUCTER = "queue-producter";
private RedisTemplate<String, Object> redisTemplate;
public QueueProducer(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Override
public void run() {
Random random = new Random();
while (true) {
try {
Thread.sleep(random.nextInt(600) + 600);
UUID queueProducerId = UUID.randomUUID();
redisTemplate.opsForList().leftPush(QUEUE_PRODUCTER, queueProducerId.toString());
log.info("生产一条数据 >>> {}", queueProducerId.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
队列消费者
package cn.stylefeng.guns.knowledge.modular.knowledge.schedule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.Random;
@Slf4j
public class QueueConsumer implements Runnable {
public static final String QUEUE_PRODUCTER = "queue-producter";
public static final String TMP_QUEUE = "tmp-queue";
private RedisTemplate<String, Object> redisTemplate;
public QueueConsumer(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Override
public void run() {
Random random = new Random();
while (true) {
Long ququeConsumerId = redisTemplate.opsForList().rightPush(QUEUE_PRODUCTER, TMP_QUEUE);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (random.nextInt(13) % 7 == 0) {
redisTemplate.opsForList().rightPush(TMP_QUEUE, QUEUE_PRODUCTER);
log.info(ququeConsumerId + "处理失败,被弹回任务队列");
} else {
redisTemplate.opsForList().rightPop(TMP_QUEUE);
log.info(ququeConsumerId + "处理成功,被清除");
}
}
}
}
测试类
@Test
public void QueueThreadTotalEntry() throws Exception {
new Thread(new QueueProducer(redisTemplate)).start();
Thread.sleep(15000);
new Thread(new QueueConsumer(redisTemplate)).start();
Thread.sleep(Long.MAX_VALUE);
}
借鉴: redis实现消息队列&发布/订阅模式使用 redisTemplate处理/获取redis消息队列
|