Hit counter ที่เก็บใน application scope จะหายเมื่อ restart web server แก้ได้โดยเก็บใน Database
วิธีแก้: ใช้ Database
- สร้างตาราง
hit_countคอลัมน์เดียวcount INT DEFAULT 0 - ทุก request:
SELECT count FROM hit_count - เพิ่มค่า:
UPDATE hit_count SET count = count + 1 - แสดงค่าใหม่
- ถ้าหน้าหลายหน้า ให้ทำซ้ำ 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 |
| Database | Persistent, แชร์ได้หลาย server | ช้ากว่า, ต้องมี DB |
| File System | Simple, persistent | Concurrency issues |
| Redis/Memcached | เร็ว, Persistent, Clusterable | ต้องมี infrastructure |