蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 JDK 8 单页/全站点击计数、会话去重、8 线程并发 AtomicInteger 与持久化恢复实测

JAVAWindows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。ExploreHitsCounter.java
ExploreHitsCounter.java181 行
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class ExploreHitsCounter {

    static String httpGet(String urlStr, String cookie) throws IOException {
        HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection();
        if (cookie != null) {
            conn.setRequestProperty("Cookie", cookie);
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        conn.disconnect();
        return sb.toString();
    }

    static String esc(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '"': sb.append("\\\""); break;
                case '\\': sb.append("\\\\"); break;
                case '\b': sb.append("\\b"); break;
                case '\f': sb.append("\\f"); break;
                case '\n': sb.append("\\n"); break;
                case '\r': sb.append("\\r"); break;
                case '\t': sb.append("\\t"); break;
                default:
                    if (c < 0x20) {
                        sb.append(String.format("\\u%04x", (int) c));
                    } else {
                        sb.append(c);
                    }
            }
        }
        return sb.toString();
    }

    static String caseJson(String name, String summary, String expected, String actual) {
        boolean passed = expected.equals(actual);
        return "    {\"name\": \"" + esc(name) + "\", \"summary\": \"" + esc(summary)
                + "\", \"expected\": \"" + esc(expected) + "\", \"actual\": \"" + esc(actual)
                + "\", \"passed\": " + passed + "}";
    }

    public static void main(String[] args) throws Exception {
        final AtomicInteger pageHitCount = new AtomicInteger(0);
        final AtomicInteger uniqueSessionHits = new AtomicInteger(0);
        final Set<String> seenSessions = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
        final AtomicInteger siteHitCount = new AtomicInteger(0);
        final List<String> filterLogs = Collections.synchronizedList(new ArrayList<String>());

        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        server.createContext("/PageHitCounter", (HttpExchange ex) -> {
            int current = pageHitCount.incrementAndGet();
            String html = "<!DOCTYPE html><html><head><title>总点击量</title></head><body>"
                    + "<h1>总点击量</h1><h2>" + current + "</h2></body></html>";
            byte[] out = html.getBytes(StandardCharsets.UTF_8);
            ex.getResponseHeaders().add("Content-Type", "text/html; charset=UTF-8");
            ex.sendResponseHeaders(200, out.length);
            OutputStream os = ex.getResponseBody();
            os.write(out);
            os.close();
        });
        server.createContext("/UniqueHit", (HttpExchange ex) -> {
            String cookie = ex.getRequestHeaders().getFirst("Cookie");
            boolean isNew = cookie != null && seenSessions.add(cookie);
            if (isNew) {
                uniqueSessionHits.incrementAndGet();
            }
            byte[] out = ("isNew=" + isNew + "|uniqueHits=" + uniqueSessionHits.get()).getBytes(StandardCharsets.UTF_8);
            ex.getResponseHeaders().add("Content-Type", "text/plain; charset=UTF-8");
            ex.sendResponseHeaders(200, out.length);
            OutputStream os = ex.getResponseBody();
            os.write(out);
            os.close();
        });
        server.createContext("/site", (HttpExchange ex) -> {
            // Simulates SiteHitCounter Filter mapped to /*
            int total = siteHitCount.incrementAndGet();
            filterLogs.add("网站访问统计:" + total);
            byte[] out = ("path=" + ex.getRequestURI().getPath() + "|siteHits=" + total).getBytes(StandardCharsets.UTF_8);
            ex.getResponseHeaders().add("Content-Type", "text/plain; charset=UTF-8");
            ex.sendResponseHeaders(200, out.length);
            OutputStream os = ex.getResponseBody();
            os.write(out);
            os.close();
        });
        server.start();
        int port = server.getAddress().getPort();
        List<String> cases = new ArrayList<String>();
        Path persistFile = Files.createTempFile("servlet-hit-counter-", ".txt");
        try {
            // Case 1: PageHitCounter across 6 requests
            String sixthBody = "";
            for (int i = 0; i < 6; i++) {
                sixthBody = httpGet("http://127.0.0.1:" + port + "/PageHitCounter", null);
            }
            String act1 = "count=" + pageHitCount.get() + "|rendersSix=" + sixthBody.contains("<h1>总点击量</h1><h2>6</h2>");
            String exp1 = "count=6|rendersSix=true";
            cases.add(caseJson("page_hit_counter_http", "实测单页点击计数器连续请求 6 次并渲染总点击量 6", exp1, act1));

            // Case 2: Session isNew() deduplicated hit counter
            String u1 = httpGet("http://127.0.0.1:" + port + "/UniqueHit", "JSESSIONID=S1");
            String u2 = httpGet("http://127.0.0.1:" + port + "/UniqueHit", "JSESSIONID=S1");
            String u3 = httpGet("http://127.0.0.1:" + port + "/UniqueHit", "JSESSIONID=S2");
            String act2 = u1 + " | " + u2 + " | " + u3;
            String exp2 = "isNew=true|uniqueHits=1 | isNew=false|uniqueHits=1 | isNew=true|uniqueHits=2";
            cases.add(caseJson("session_unique_hit_dedup", "实测基于会话 isNew() 判断的去重点击计数", exp2, act2));

            // Case 3: Site-wide Filter hit counter across 5 distinct routes
            String[] routes = {"/site/", "/site/docs", "/site/about", "/site/api", "/site/contact"};
            for (String route : routes) {
                httpGet("http://127.0.0.1:" + port + route, null);
            }
            String act3 = "total=" + siteHitCount.get() + "|firstLog=" + filterLogs.get(0) + "|lastLog=" + filterLogs.get(4);
            String exp3 = "total=5|firstLog=网站访问统计:1|lastLog=网站访问统计:5";
            cases.add(caseJson("site_filter_hit_counter", "实测全站过滤器拦截 5 个不同路径并按序输出访问统计日志", exp3, act3));

            // Case 4: Multi-threaded AtomicInteger safety + destroy/init persistence
            final AtomicInteger concurrentCounter = new AtomicInteger(0);
            ExecutorService pool = Executors.newFixedThreadPool(8);
            final CountDownLatch latch = new CountDownLatch(8);
            for (int t = 0; t < 8; t++) {
                pool.submit(() -> {
                    for (int k = 0; k < 50; k++) {
                        concurrentCounter.incrementAndGet();
                    }
                    latch.countDown();
                });
            }
            latch.await();
            pool.shutdown();
            // Simulate destroy() persisting to storage and init() reloading
            Files.write(persistFile, String.valueOf(concurrentCounter.get()).getBytes(StandardCharsets.UTF_8));
            int reloaded = Integer.parseInt(new String(Files.readAllBytes(persistFile), StandardCharsets.UTF_8).trim());
            String act4 = "concurrent=" + concurrentCounter.get() + "|reloadedAfterRestart=" + reloaded;
            String exp4 = "concurrent=400|reloadedAfterRestart=400";
            cases.add(caseJson("concurrent_atomic_counter_and_persistence", "实测 8 线程并发 AtomicInteger 计数无丢失与 destroy/init 持久化恢复", exp4, act4));
        } finally {
            server.stop(0);
            Files.deleteIfExists(persistFile);
        }

        System.out.println("{");
        System.out.println("  \"version\": \"Eclipse Adoptium OpenJDK " + esc(System.getProperty("java.version")) + "\",");
        System.out.println("  \"cases\": [");
        for (int i = 0; i < cases.size(); i++) {
            System.out.println(cases.get(i) + (i + 1 < cases.size() ? "," : ""));
        }
        System.out.println("  ]");
        System.out.println("}");
    }
}
本例需在 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。

入口文件:projects/servlet-hits-counter-lab/ExploreHitsCounter.java

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 ExploreHitsCounter.java,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Servlet

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1373.zip

下载课程关联工程包:Servlet

课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a1361.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习