概念:
DelayQueue是一个无界阻塞队列,用于放置实现了Delayed接口的对象,只有在延迟期满时才能从中提取元素。该队列时有序的,即队列的头部是延迟期满后保存时间最长的Delayed 元素。注意:不能将null元素放置到这种队列中。
项目场景:店铺取票后五分钟内没有出票,即收回所取的票
实现:
step1 创建接口里需要放的对象类型,实现Delayed
public class OrderInfoDelayBean extends OrderInfo implements Delayed {
//必须实现Delayed接口,重写compareTo方法。该方法提供一个和getDelay方法一致的排序。即从队列里取过期元素的顺序即按照此顺序。
private static final long serialVersionUID = 6255640460985141483L;
private long dueTime;
@Override
public int compareTo(Delayed o) {
final OrderInfoDelayBean other = (OrderInfoDelayBean) o;
if (this.dueTime<other.dueTime) {
return -1;
} else if (this.getLastPrintDate().after(other.getLastPrintDate())) {
return 1;
}
return 0;
}
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(dueTime - new Date().getTime(), TimeUnit.NANOSECONDS);
}
public long getDueTime() {
return dueTime;
}
public void setDueTime(long dueTime) {
this.dueTime = dueTime;
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
final OrderInfoDelayBean other = (OrderInfoDelayBean) obj;
if (!this.getSerialNumber().equals(other.getSerialNumber())) {
return false;
}
return true;
}
}
step2
执行任务的类里定义一个静态变量DelayQueue,每次店铺取票时,new一个delayBean,过期时间设置为当前时间加5min,将delayBean放入队列
public class OrderInfoManager {
private static Logger logger = Logger.getLogger(OrderInfoManager.class);
public static DelayQueue<OrderInfoDelayBean> DELAY_QUEUE = new DelayQueue<>();
public static void addOrderInfoDelay(OrderInfoVo orderInfoVo){
//转换成OrderInfoDelayBean再加入队列
OrderInfoDelayBean orderInfoDelayBean = new OrderInfoDelayBean();
try {
BeanUtils.copyProperties(orderInfoDelayBean, orderInfoVo);
} catch (Exception e) {
logger.error("将订单加入队列时,copy出错");
logger.error(e.getMessage(),e.fillInStackTrace());
}
orderInfoDelayBean.setDueTime(new Date().getTime()+300000);
if(!DELAY_QUEUE.contains(orderInfoDelayBean)){
DELAY_QUEUE.add(orderInfoDelayBean);
logger.info("订单"+orderInfoDelayBean.getSerialNumber()+"进入延时队列,当前时间"+new Date().getTime());
}
}
}
step3
写一个定时任务,while((orderInfoDelayBean=DELAY_QUEUE.take())!=null) {} 过期时会自动拿到,拿到后按照需求执行操作。拿不到时,take()方法会一直阻塞,所以虽然是定时任务,实际执行一次后就阻塞着不会再多次执行了
public void deleteTimeUpOrderInfo() throws InterruptedException {
logger.info("=-=-=-=-=-=-=-=-=-=-= 清除下派给散铺的过期订单开始");
OrderInfoDelayBean orderInfoDelayBean = null;
while((orderInfoDelayBean=DELAY_QUEUE.take())!=null) {
logger.info("=-=-=-=-=-=-=-=-=-=-= 清除下派给散铺的过期订单【"+orderInfoDelayBean.getSerialNumber()+"】成功,当前时间"+new Date().getTime());
//更新订单打印状态、店铺id、下发时间
orderService.recallOrderFromStore(orderInfoDelayBean.getSerialNumber());
//更新订单下的票打印状态、店铺id、下发时间
ticketService.recallTicketFromStore(orderInfoDelayBean.getSerialNumber());
}
}
相关配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"
default-autowire="byName" default-lazy-init="true">
<bean id="orderInfoManager" class="com.latech.order.manager.OrderInfoManager"></bean>
<bean id="getOrderInfoFormDBTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref bean="orderInfoManager" />
</property>
<property name="targetMethod">
<value>getOrderInfoFormDB</value>
</property>
<property name="concurrent">
<value>false</value>
</property>
</bean>
<bean id="clearIssuedOrderInfoTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref bean="orderInfoManager" />
</property>
<property name="targetMethod">
<value>clearIssuedOrderInfo</value>
</property>
<property name="concurrent">
<value>false</value>
</property>
</bean>
<bean id="deleteTimeUpOrderInfoTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref bean="orderInfoManager" />
</property>
<property name="targetMethod">
<value>deleteTimeUpOrderInfo</value>
</property>
<property name="concurrent">
<value>false</value>
</property>
</bean>
<!-- 调度触发器 -->
<bean id="getOrderInfoFormDBDoTime" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<property name="jobDetail">
<ref bean="getOrderInfoFormDBTask" />
</property>
<property name="startDelay" value="0" />
<property name="repeatInterval" value="5000" />
</bean>
<!-- 调度触发器 -->
<bean id="clearIssuedOrderInfoDoTime" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<property name="jobDetail">
<ref bean="clearIssuedOrderInfoTask" />
</property>
<property name="startDelay" value="0" />
<property name="repeatInterval" value="3000" />
</bean>
<!-- 调度触发器 -->
<bean id="deleteTimeUpOrderInfoDoTime" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<property name="jobDetail">
<ref bean="deleteTimeUpOrderInfoTask" />
</property>
<property name="startDelay" value="0" />
<property name="repeatInterval" value="100" />
</bean>
<bean autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="getOrderInfoFormDBDoTime" />
<ref bean="clearIssuedOrderInfoDoTime" />
<ref bean="deleteTimeUpOrderInfoDoTime" />
</list>
</property>
</bean>
</beans>
注意:
此配置里除了deleteTimeUpOrderInfoTask任务,还有其它任务,此处特意把配置放上来,是因为这里有一个需要特别注意的问题
- 使用注解@Schedule配置时,由于take()方法是阻塞的,影响到其它定时任务的执行
- 给方法再加一个注解@Async,类加上@EnableAsync时,定时任务都可以执行了,但这里就有一个问题,take()变得不阻塞了
所以最后采取xml如上配置实现
网友评论