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 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
| public class LogSpout extends BaseRichSpout { private SpoutOutputCollector collector; private BufferedReader reader; @Override public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { this.collector = collector; try { this.reader = new BufferedReader(new FileReader("/var/log/access.log")); } catch (IOException e) { throw new RuntimeException("无法打开日志文件", e); } } @Override public void nextTuple() { try { String logLine = reader.readLine(); if (logLine != null) { collector.emit(new Values(logLine, System.currentTimeMillis())); } else { Thread.sleep(50); } } catch (IOException | InterruptedException e) { e.printStackTrace(); } } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("logline", "timestamp")); } }
public class LogParserBolt extends BaseRichBolt { private OutputCollector collector; private Pattern logPattern; @Override public void prepare(Map config, TopologyContext context, OutputCollector collector) { this.collector = collector; String regex = "^(\\S+) \\S+ \\S+ \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(\\S+) (\\S+) \\S+\" (\\d{3}) (\\d+)"; this.logPattern = Pattern.compile(regex); } @Override public void execute(Tuple tuple) { try { String logLine = tuple.getStringByField("logline"); long timestamp = tuple.getLongByField("timestamp"); Matcher matcher = logPattern.matcher(logLine); if (matcher.find()) { String clientIP = matcher.group(1); String method = matcher.group(3); String url = matcher.group(4); int statusCode = Integer.parseInt(matcher.group(5)); long responseSize = Long.parseLong(matcher.group(6)); collector.emit(tuple, new Values( clientIP, method, url, statusCode, responseSize, timestamp )); } collector.ack(tuple); } catch (Exception e) { collector.fail(tuple); } } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("client_ip", "method", "url", "status_code", "response_size", "timestamp")); } }
public class ErrorDetectionBolt extends BaseRichBolt { private OutputCollector collector; private Map<String, AtomicInteger> errorCounts; private ScheduledExecutorService scheduler; @Override public void prepare(Map config, TopologyContext context, OutputCollector collector) { this.collector = collector; this.errorCounts = new ConcurrentHashMap<>(); this.scheduler = Executors.newScheduledThreadPool(1); scheduler.scheduleAtFixedRate(this::checkErrorRates, 1, 1, TimeUnit.MINUTES); } @Override public void execute(Tuple tuple) { try { String clientIP = tuple.getStringByField("client_ip"); int statusCode = tuple.getIntegerByField("status_code"); if (statusCode >= 400) { errorCounts.computeIfAbsent(clientIP, k -> new AtomicInteger(0)) .incrementAndGet(); collector.emit(tuple, new Values( clientIP, statusCode, "ERROR_DETECTED", System.currentTimeMillis() )); } collector.ack(tuple); } catch (Exception e) { collector.fail(tuple); } } private void checkErrorRates() { for (Map.Entry<String, AtomicInteger> entry : errorCounts.entrySet()) { String ip = entry.getKey(); int errorCount = entry.getValue().getAndSet(0); if (errorCount > 10) { System.out.println("高错误率警告: IP " + ip + " 在过去1分钟内产生了 " + errorCount + " 个错误"); sendAlert(ip, errorCount); } } } private void sendAlert(String ip, int errorCount) { System.out.println("发送告警: IP " + ip + " 错误数: " + errorCount); } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("client_ip", "status_code", "event_type", "timestamp")); } }
public class StatsBolt extends BaseRichBolt { private OutputCollector collector; private Map<String, Long> urlCounts; private Map<String, Long> ipCounts; private AtomicLong totalRequests; @Override public void prepare(Map config, TopologyContext context, OutputCollector collector) { this.collector = collector; this.urlCounts = new ConcurrentHashMap<>(); this.ipCounts = new ConcurrentHashMap<>(); this.totalRequests = new AtomicLong(0); ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.scheduleAtFixedRate(this::printStats, 30, 30, TimeUnit.SECONDS); } @Override public void execute(Tuple tuple) { try { String clientIP = tuple.getStringByField("client_ip"); String url = tuple.getStringByField("url"); urlCounts.merge(url, 1L, Long::sum); ipCounts.merge(clientIP, 1L, Long::sum); totalRequests.incrementAndGet(); collector.ack(tuple); } catch (Exception e) { collector.fail(tuple); } } private void printStats() { System.out.println("=== 实时统计 ==="); System.out.println("总请求数: " + totalRequests.get()); System.out.println("Top 10 热门URL:"); urlCounts.entrySet().stream() .sorted(Map.Entry.<String, Long>comparingByValue().reversed()) .limit(10) .forEach(entry -> System.out.println(" " + entry.getKey() + ": " + entry.getValue())); System.out.println("Top 10 活跃IP:"); ipCounts.entrySet().stream() .sorted(Map.Entry.<String, Long>comparingByValue().reversed()) .limit(10) .forEach(entry -> System.out.println(" " + entry.getKey() + ": " + entry.getValue())); } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { } }
|