利用阻塞队列完成异步操作

    //异步阻塞队列变量
    private BlockingQueue<VoucherOrder> orderTasks=new ArrayBlockingQueue<>(1024*1024);
    //create the thread pool signal thread
    private static final ExecutorService SECKILL_ORDER_EXECUTOR=Executors.newSingleThreadExecutor();
    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }
    private class VoucherOrderHandler implements Runnable{

        @Override
        public void run() {
            while(true){
                //get orderinfo from blockingqueen
                try {
                    //获取队列
                    VoucherOrder voucherOrder = orderTasks.take();
                    //crate voucherOrder
                    //执行操作
                    handlerVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    log.error(e.getMessage().toString());
                    //throw new RuntimeException(e);
                }


            }
        }
    }      

private  IVoucherOrderService proxy;


private
void handlerVoucherOrder(VoucherOrder voucherOrder) { // user ID long userID= voucherOrder.getUserId(); RLock lock=redisson.getLock(RedisConstants.LOCK_VOUCHERORDER_KEY+ StrUtil.toString(userID)); boolean islock = lock.tryLock();//active watch dog if(!islock) { log.error("锁创建失败"); } try { //IVoucherOrderService proxy=(IVoucherOrderService)AopContext.currentProxy();//获取spring 对当前对象的代理 proxy.createVoucherOrderByObj(voucherOrder); } catch (IllegalStateException e) { throw new RuntimeException(e); }finally { //lock.unLock(); //my define simple redis lock lock.unlock();//redisson release lock } }

 

 在阻塞队列中增加任务

 //6创建订单
        VoucherOrder vo=new VoucherOrder();
        //6.1 订单ID

        vo.setId(orderid);

        vo.setUserId(userID);
        //6.3 voucher ID
        vo.setVoucherId(voucherId);
        orderTasks.add(vo);// save the voucherorder to blockingQueen

        proxy=(IVoucherOrderService)AopContext.currentProxy();

 

@PostConstruct

该注解可以实现在运行工程时,自动运行该注解下的方法;

@PostConstruct是java5的时候引入的注解,指的是在项目启动的时候执行这个方法,也可以理解为在spring容器启动的时候执行,可作为一些数据的常规化加载,比如数据字典之类的。

 

 被@PostConstruct修饰的方法会在服务器加载Servle的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行

也就是加载顺序 

 服务器加载Servlet -> servlet 构造函数的加载 -> postConstruct ->init(init是在service 中的初始化方法. 创建service 时发生的事件.) ->Service->destory->predestory->服务器卸载serlvet

在spring中Constructor、@Autowired、@PostConstruct的顺序
Constructor >> @Autowired >> @PostConstruct

 

posted on 2023-03-08 17:23  hztech  阅读(41)  评论(0编辑  收藏  举报

导航