GpsDataBuffer.java 2.14 KB
package com.bsth.client;

import com.bsth.Application;
import com.bsth.entity.GpsEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;

/**
 * 定时定距数据
 */
@Component
public class GpsDataBuffer implements CommandLineRunner {

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

    static Logger logger = LoggerFactory.getLogger(GpsDataBuffer.class);

    public void put(GpsEntity gps) {
        try {
            if(null == gps)
                return;

            linkedList.add(gps);
            size++;
        } catch (Exception e) {
            logger.error("", e);
        }
    }

    public static List<GpsEntity> pollAll() {
        List<GpsEntity> rs = new ArrayList<>(300);
        GpsEntity gps;

        while (true) {
            gps = linkedList.poll();
            if (gps == null) {
                size = 0;
                break;
            }
            rs.add(gps);
        }

        //logger.info("poll size: " + rs.size() + " -current size: " + size);
        return rs;
    }

    /**
     * 清理数据,保持最大 MAX_SIZE 个数的元素
     */
    public static void clear() {
        if (size <= MAX_SIZE)
            return;
        int len = size - MAX_SIZE;
        for (int j = 0; j < len; j++) {
            linkedList.poll();
            size--;
        }
        logger.info("clear size: " + len + " -current size: " + size);
    }

    @Autowired
    BufferSizeCheck bufferSizeCheck;

    @Override
    public void run(String... args) {
        Application.mainServices.scheduleWithFixedDelay(bufferSizeCheck, 60, 30, TimeUnit.SECONDS);
    }

    @Component
    public static class BufferSizeCheck extends Thread {

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