1 package us.codecraft.webmagic.monitor;
2
3 import org.slf4j.Logger;
4 import org.slf4j.LoggerFactory;
5 import us.codecraft.webmagic.Spider;
6 import us.codecraft.webmagic.scheduler.MonitorableScheduler;
7
8 import java.util.Date;
9 import java.util.List;
10
11
12
13
14
15 public class SpiderStatus implements SpiderStatusMXBean {
16
17 protected final Spider spider;
18
19 protected Logger logger = LoggerFactory.getLogger(getClass());
20
21 protected final SpiderMonitor.MonitorSpiderListener monitorSpiderListener;
22
23 public SpiderStatus(Spider spider, SpiderMonitor.MonitorSpiderListener monitorSpiderListener) {
24 this.spider = spider;
25 this.monitorSpiderListener = monitorSpiderListener;
26 }
27
28 public String getName() {
29 return spider.getUUID();
30 }
31
32 public int getLeftPageCount() {
33 if (spider.getScheduler() instanceof MonitorableScheduler) {
34 return ((MonitorableScheduler) spider.getScheduler()).getLeftRequestsCount(spider);
35 }
36 logger.warn("Get leftPageCount fail, try to use a Scheduler implement MonitorableScheduler for monitor count!");
37 return -1;
38 }
39
40 public int getTotalPageCount() {
41 if (spider.getScheduler() instanceof MonitorableScheduler) {
42 return ((MonitorableScheduler) spider.getScheduler()).getTotalRequestsCount(spider);
43 }
44 logger.warn("Get totalPageCount fail, try to use a Scheduler implement MonitorableScheduler for monitor count!");
45 return -1;
46 }
47
48 @Override
49 public int getSuccessPageCount() {
50 return monitorSpiderListener.getSuccessCount().get();
51 }
52
53 @Override
54 public int getErrorPageCount() {
55 return monitorSpiderListener.getErrorCount().get();
56 }
57
58 public List<String> getErrorPages() {
59 return monitorSpiderListener.getErrorUrls();
60 }
61
62 @Override
63 public String getStatus() {
64 return spider.getStatus().name();
65 }
66
67 @Override
68 public int getThread() {
69 return spider.getThreadAlive();
70 }
71
72 public void start() {
73 spider.start();
74 }
75
76 public void stop() {
77 spider.stop();
78 }
79
80 @Override
81 public Date getStartTime() {
82 return spider.getStartTime();
83 }
84
85 @Override
86 public int getPagePerSecond() {
87 if (getStartTime() != null) {
88 int runSeconds = (int) (System.currentTimeMillis() - getStartTime().getTime()) / 1000;
89 if (runSeconds != 0) {
90 return getSuccessPageCount() / runSeconds;
91 }
92 }
93 return -1;
94 }
95
96 }