/**
* @author hyx
* 考试队列
*/
@Service
public class ExamQueueService implements InitializingBean {
//队列名
public final String QUEUE_NAME = "examRecord";
@Autowired
private RedisTemplate redisTemplate;
/**
* 入队
*/
public Long enqueue(Object record) {
JSONObject object = new JSONObject();
object.put("record", record);
return redisTemplate.opsForList().leftPush(this.QUEUE_NAME, object);
}
/**
* 出队
*/
public Object dequeue() {
Object o = redisTemplate.opsForList().rightPop(this.QUEUE_NAME);
return o;
}
/**
* 消费队列(此方法在Spring容器初始化的时候执行)
*/
@Override
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void afterPropertiesSet() {
//启用一个线程来消费队列,将数据从队列中取出来并入库
//数据库性能允许的情况下,可以启用多个线程
Thread t = new Thread(() -> {
while (true) {
try {
//从队列中获取一条数据(获取后队列中会自动删除此数据)
Object dequeue = this.dequeue();
if (dequeue == null) {
//如果队列为空,则休眠一秒
Thread.sleep(1000L);
} else {
//数据入库...略
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
}
}