Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

วิธีทำ Hit Counter ไม่หายเมื่อ Restart Application ใน JSP

Hit counter ที่เก็บใน application scope จะหายเมื่อ restart web server แก้ได้โดยเก็บใน Database

วิธีแก้: ใช้ Database

  1. สร้างตาราง hit_count คอลัมน์เดียว count INT DEFAULT 0
  2. ทุก request: SELECT count FROM hit_count
  3. เพิ่มค่า: UPDATE hit_count SET count = count + 1
  4. แสดงค่าใหม่
  5. ถ้าหน้าหลายหน้า ให้ทำซ้ำ logic นี้ทุกหน้า

ตัวอย่าง Pseudocode

<%
    // 1. Connect DB (ใช้ DataSource/Connection pool)
    Connection conn = dataSource.getConnection();
    
    // 2. Read current count
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT count FROM hit_count");
    int count = 0;
    if (rs.next()) count = rs.getInt("count");
    
    // 3. Increment
    count++;
    stmt.executeUpdate("UPDATE hit_count SET count = " + count);
    
    // 4. Display
    out.println("Total visits: " + count);
    
    rs.close(); stmt.close(); conn.close();
%>

แนวทางปฏิบัติที่ดีกว่า

  • ใช้ Connection Pool (HikariCP, DBCP, Tomcat JDBC Pool)
  • ใช้ PreparedStatement ป้องกัน SQL Injection
  • Cache count ใน memory (application scope) sync ไป DB ทุก N วินาที/requests
  • หรือใช้ Redis/In-memory store สำหรับ high traffic
  • Google Analytics / Matomo สำหรับ analytics จริง (ดีกว่า counter เอง)

สรุป

วิธีข้อดีข้อเสีย
Application Scopeง่าย, เร็วหายตอน restart
DatabasePersistent, แชร์ได้หลาย serverช้ากว่า, ต้องมี DB
File SystemSimple, persistentConcurrency issues
Redis/Memcachedเร็ว, Persistent, Clusterableต้องมี infrastructure