GpsBeforeBuffer.java
2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
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();
}
}
}