GpsBeforeBuffer.java 2.66 KB
package com.bsth.client;

import com.bsth.entity.GpsEntity;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * 从 socket client 到调度系统 的缓冲
 * Created by panzhao on 2017/5/4.
 */
@Component
@Order(2)
public class GpsBeforeBuffer implements CommandLineRunner{

    static LinkedList<GpsEntity> linkedList = new LinkedList();
    static final int MAX_SIZE = 4000 * 20;

    public void put(GpsEntity gps){
        if(gps == null || StringUtils.isBlank(gps.getDeviceId()))
            return;

        linkedList.add(gps);
    }

    static Logger log = LoggerFactory.getLogger(GpsBeforeBuffer.class);

    public static List<GpsEntity> pollAll(){
        List<GpsEntity> rs = new ArrayList<>(300);
        GpsEntity gps;
        int size = linkedList.size();
        for(int j = 0; j < size; j++){
            gps = linkedList.poll();
            rs.add(gps);
        }
        /*while (true){
            gps = linkedList.poll();
            if(gps == null){
                break;
            }
            rs.add(gps);
        }*/

        log.info("poll size: " + rs.size());
        return rs;
    }

    /**
     * 清理数据,保持最大 MAX_SIZE 个数的元素
     */
    public static void clear(){
        int size = linkedList.size();
        if(size <= MAX_SIZE)
            return;

        int len = size - MAX_SIZE;
        for(int j = 0; j < len; j++){
            linkedList.poll();
        }
        log.info("clear size: " + len);
    }

    @Autowired
    BufferSizeCheck bufferSizeCheck;

    ScheduledExecutorService sexec;

    @Override
    public void run(String... strings) throws Exception {
        sexec = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setName("gpsBufferSizeCheck");
                return t;
            }
        });
        sexec.scheduleWithFixedDelay(bufferSizeCheck, 60, 30, TimeUnit.SECONDS);
    }

    @Component
    public static class BufferSizeCheck extends Thread {

        @Override
        public void run() {
            GpsBeforeBuffer.clear();
        }
    }
}