有时要为每一篇文章统计其点击次数,如果每一次浏览都要更新一次库的话,那性能在访问量很大的情况下,服务器的压力就会很大了,比较好一点的方法就是先将要更新的数据缓存起来,然后每隔一段时间再利用数据库的批量处理,批量更新库。源码如下:
半分钟更新一次计数.
count包中三个*.java文件
1.CountBean.java
package count;
public class CountBean { private String countType;
int countId;
public CountBean() { }
public void setCountType(String countTypes) { this.countType = countTypes; }
public void setCountId(int countIds) { this.countId = countIds; }
public String getCountType() { return countType; }
public int getCountId() { return countId; } }
2 CountCache.java
package count;
import java.util.*;
public class CountCache { public static LinkedList list = new LinkedList();
public CountCache() { }
public static void add(CountBean cb) { if (cb != null) { list.add(cb); } }
} 3.CountControl.java
package count;
import java.sql.*; import com.pp.db.*;
public class CountControl { private static long lastExecuteTime = 0;// 上次更新时间
private static long executeSep = 30000;// 定义更新间隔时间,单位毫秒 半分钟
public CountControl() { }
public synchronized void executeUpdate() { Connection conn = null; PreparedStatement ps = null; try { conn = new DBConnection().getConn(); conn.setAutoCommit(false); ps = conn .prepareStatement("update t_news set hits=hits+1 where id=?"); for (int i = 0; i < CountCache.list.size(); i++) { CountBean cb = (CountBean) CountCache.list.getFirst(); CountCache.list.removeFirst(); ps.setInt(1, cb.getCountId()); ps.executeUpdate(); // ps.addBatch(); } // int[] counts = ps.executeBatch(); conn.commit(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (ps != null) { ps.clearParameters(); ps.close(); ps = null; conn.close(); } } catch (SQLException e) { }
} }
public long getLast() { return lastExecuteTime; }
public void run(){ long now = System.currentTimeMillis(); if ((now - lastExecuteTime) > executeSep) { System.out.print("lastExecuteTime:"+lastExecuteTime); System.out.print(" now:"+now+"/n"); System.out.print(" sep="+(now - lastExecuteTime)+"/n"); lastExecuteTime=now; executeUpdate(); } else{ System.out.print("wait for "+(now - lastExecuteTime)+" seconds:"+"/n"); } } }
4.使用
<% CountBean cb=new CountBean(); cb.setCountId(Integer.parseInt(request.getParameter("cid"))); //计数的资源id CountCache.add(cb); System.out.print(CountCache.list.size()+"<br>"); CountControl c=new CountControl(); c.run(); System.out.print(CountCache.list.size()+"<br>"); %>
文章原贴: