Development of log interface based on blocking queue

preface

Recently, a log interface has been developed for other systems to call through web service. Considering concurrency, multithreading decides to use blocking queue to implement log interface. Record the implementation process for your reference. If you don't understand the blocking queue, you can refer to the previous blog post.

Implement blocking queue

public class RemoteUpgradeLogQueue {

     private static RemoteUpgradeLogQueue remoteUpgradeLogQueue  = new RemoteUpgradeLogQueue();

     //定义一个阻塞队列

     private <u>BlockingQueue</u> blockingQueue = new 
LinkedBlockingQueue<>();

     private RemoteUpgradeLogQueue(){}

     public static RemoteUpgradeLogQueue getInstance(){

           return remoteUpgradeLogQueue;

     }

     public Boolean push(RemoteUpgradeLogInfo 
remoteUpgradeLogInfo){

           return <u>this</u><u>.</u><u>blockingQueue</u><u>.add(</u><u>remoteUpgradeLogInfo</u><u>)</u>;

     }

     public RemoteUpgradeLogInfo pop(){

           RemoteUpgradeLogInfo remoteUpgradeLogInfo = null;

           try {

                remoteUpgradeLogInfo = (RemoteUpgradeLogInfo) 
this.blockingQueue.take();

           } catch (InterruptedException e) {

                System.out.println("从队列中取出日志错误!");

           }

           return remoteUpgradeLogInfo;

     }

     public int size(){

           return this.blockingQueue.size();

     }

}

Define consumer

The method called by the service is the specific log processing method

@Component

public class DealRemoteUpgradeLogQueue {



     @Autowired

     private RemoteUpgradeLogService remoteUpgradeLogService;

     

     @postconstruct

     public void startLogThread(){

           ExecutorService e = Executors.newFixedThreadPool(1);

           e.submit(new PopLogInfo(remoteUpgradeLogService));

     }

     

     class PopLogInfo implements Runnable {

           RemoteUpgradeLogService remoteUpgradeLogService;



        public PopLogInfo(RemoteUpgradeLogService 
remoteUpgradeLogService) {

            this.remoteUpgradeLogService = 
remoteUpgradeLogService;

        }



        @Override

        public void run() {

            while (true) {

                try {

                  RemoteUpgradeLogInfo remoteUpgradeLogInfo = RemoteUpgradeLogQueue.getInstance().pop();

                    if(remoteUpgradeLogInfo!=null){

                        remoteUpgradeLogService.saveLogInfo(remoteUpgradeLogInfo);

                    }

                } catch (Exception e) {

                    e.printStackTrace();

                }

            }

        }

    }
}


Realization producer

The producer can directly push into the opposite column.

RemoteUpgradeLogQueue.getInstance().push(remoteUpgradeLogInfo);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>