最近我们的SNS游戏搞了一个LV包时尚活动,以下代码是做排行榜的实例。
代码区:
package cn.org.cute.flash.doing;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.logicalcobwebs.proxool.ProxoolException;
import org.logicalcobwebs.proxool.ProxoolFacade;
import cn.org.cute.internation.SourceInternation;
import cn.org.cute.sys.CuteConstants;
import cn.org.cute.sys.ThaliaCookieMgr;
import cn.org.dbcache.MemcachedUtil;
import com.danga.MemCached.MemCachedClient;
import flex.messaging.FlexContext;
public class CuteLVRankDoingImpl {
//更新间隔
public static long ONE_DAY_MILLI_SECOND = 15*60*1000L;
public static String RERANK_TIME = "12:00:00";
private static final String SSQL = "select CU_UID,CU_LVNUM from cute_lv where CU_UID = ?";
private static final String USQL = "UPDATE cute_lv set CU_LVNUM=? where CU_UID=?";
private static final String ISQL = "INSERT INTO cute_lv(CU_LVNUM,CU_UID) VALUES(?,?)";
private static final String proxool = "proxool.rank";
private static final String URL = "proxool.rank:com.mysql.jdbc.Driver:" + CuteConstants.CONN_RANK_URL;
static{
try {
Class.forName("org.logicalcobwebs.proxool.ProxoolDriver").newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 创建连接
* @return
* <house-keeping-sleep-time>90000</house-keeping-sleep-time>
<maximum-new-connections>20</maximum-new-connections>
<prototype-count>5</prototype-count>
<maximum-connection-count>1000</maximum-connection-count>
<minimum-connection-count>10</minimum-connection-count>
*/
public synchronized static Connection createConnection(){
Connection conn = null;
Properties pro = new Properties();
pro.setProperty("house-keeping-sleep-time", "90000");
pro.setProperty("maximum-new-connections", "20");
pro.setProperty("prototype-count", "5");
pro.setProperty("proxool.maximum-connection-count", "1000");
pro.setProperty("minimum-connection-count", "10");
//info.setProperty("user", "sa");
//info.setProperty("password", "");
try {
ProxoolFacade.registerConnectionPool(URL, pro);
conn = DriverManager.getConnection(proxool);
} catch (ProxoolException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 插入数据
* @param conn
* @param cuID
* @param lvNum
* @return
*/
public static int insertCuteLV(int cuID,int lvNum){
Connection conn = createConnection();
if(conn == null){
System.out.println("insertCuteLV----conn is null");
return 0;
}
String sql = "INSERT INTO cute_lv(CU_UID,CU_LVNUM) VALUES(?,?)";
PreparedStatement pst = null;
try {
conn.setAutoCommit(false);
pst = conn.prepareStatement(sql);
pst.setInt(1,cuID);
pst.setInt(2, lvNum);
int count = pst.executeUpdate();
try {conn.commit();} catch (SQLException e1) {e1.printStackTrace();}
return count;
} catch (SQLException e) {
e.printStackTrace();
try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
}finally{
destroy(pst,conn);
}
return 0;
}
/**
* 更新数据
* @param conn
* @param cuID
* @param cuName
* @param lvNum
* @return
*/
public static int updateCuteLV(int cuID,int lvNum){
Connection conn = createConnection();
if(conn == null){
System.out.println("updateCuteLV----conn is null");
return 0;
}
String sql = "UPDATE cute_lv set CU_LVNUM=? where CU_UID=?";
PreparedStatement pst = null;
try {
conn.setAutoCommit(false);
pst = conn.prepareStatement(sql);
pst.setInt(1, lvNum);
pst.setInt(2,cuID);
int count = pst.executeUpdate();
try {conn.commit();} catch (SQLException e1) {e1.printStackTrace();}
return count;
} catch (SQLException e) {
e.printStackTrace();
try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
}finally{
destroy(pst,conn);
}
return 0;
}
/**
* 创建LVRANK表数据
* @param queryConn
* @param insertConn
*/
public static void createLVRank(){
Connection conn = createConnection();
if(conn == null){
System.out.println("queryLVRank----conn is null");
return ;
}
String truncate_sql = "truncate cute_lvrank";
String insert_sql = "INSERT INTO cute_lvrank(CU_UID,CU_LVNUM) (select CU_UID,CU_LVNUM from cute_lv order by CU_LVNUM desc)";
PreparedStatement delpst = null;
PreparedStatement insertpst = null;
try {
conn.setAutoCommit(false);
delpst = conn.prepareStatement(truncate_sql);
insertpst = conn.prepareStatement(insert_sql);
delpst.executeUpdate();
insertpst.executeUpdate();
try {conn.commit();} catch (SQLException e1) {e1.printStackTrace();}
} catch (SQLException e) {
e.printStackTrace();
try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
}finally{
destroy(delpst,insertpst,conn);
}
}
/**
* uid用户每成功卖一次时尚包包 lvnum加1
* @param uid
* @return
*/
public static int addOrUpdateLvNum(long uid,int addNum){
Connection conn = createConnection();
if(conn == null){
System.out.println("logger-------addOrUpdateLvNum connection is null------uid:"+uid+"---------addlvNUM:"+addNum);
return 0;
}
String update_sql = "";
PreparedStatement pst = null;
PreparedStatement update_pst = null;
ResultSet res = null;
int count = 0;
try {
conn.setAutoCommit(false);
pst = conn.prepareStatement(SSQL);
pst.setInt(1, (int)uid);
res = pst.executeQuery();
if(res.next()){//判断是否是初次加工LV包
count = res.getInt("CU_LVNUM");
update_sql = USQL;
}else{
update_sql = ISQL;
}
update_pst = conn.prepareStatement(update_sql);
update_pst.setInt(1,count+addNum);
update_pst.setInt(2,(int)uid);
count = update_pst.executeUpdate();
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
}finally{
destroy(pst,update_pst,conn);
}
return count;
}
public static HashMap<String,String> getLVRank(long uid,int start,int end){
Connection conn = createConnection();
if(conn == null){
System.out.println("------------getLVRank connection is null");
return null;
}
String sql = "select CU_RANK,CU_UID,CU_LVNUM from cute_lvrank where CU_RANK between ? and ? or CU_UID = ?";
PreparedStatement pst = null;
ResultSet res = null;
HashMap map = new HashMap();
try {
pst = conn.prepareStatement(sql);
pst.setInt(1, start);
pst.setInt(2, end);
pst.setInt(3, (int)uid);
res = pst.executeQuery();
while(res.next()){
map.put(""+res.getInt("CU_RANK"), res.getInt("CU_UID")+"/"+res.getInt("CU_LVNUM"));
}
return map;
} catch (SQLException e) {
e.printStackTrace();
}finally{
destroy(res,pst,conn);
}
return null;
}
/**
* 释放资源
* @param objs
*/
private static void destroy(Object...objs ){
if(objs == null || objs.length == 0){
return ;
}
try {
for(Object obj:objs){
if(obj instanceof Connection){
Connection conn = (Connection)obj;
if(conn != null ){conn.close();conn = null;}
}else if(obj instanceof PreparedStatement){
PreparedStatement pst = (PreparedStatement)obj;
if(pst !=null ){pst.close();pst = null;}
}else if(obj instanceof ResultSet){
ResultSet res = (ResultSet)obj;
if(res !=null ){res.close();res = null;}
}else if(obj instanceof Statement){
Statement st = (Statement)obj;
if(st!=null){st.close();st = null;}
}else{
System.out.println("method of destroy's objs is valid!");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void batchInsertCuteLV(){
Connection conn = createConnection();
if(conn == null){
System.out.println("insertCuteLV----conn is null");
return ;
}
String sql = "INSERT INTO cute_lv(CU_UID,CU_LVNUM) VALUES(?,?)";
PreparedStatement pst = null;
try {
conn.setAutoCommit(false);
pst = conn.prepareStatement(sql);
for(int i=200000;i<300000;i++){
pst.setInt(1,i);
pst.setInt(2,i);
pst.addBatch();
}
pst.executeBatch();
pst.clearBatch();
try {conn.commit();} catch (SQLException e1) {e1.printStackTrace();}
} catch (SQLException e) {
e.printStackTrace();
try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
}finally{
destroy(pst,conn);
}
}
/**
* 得到全服排行。
* @param params
* @return
*/
public static HashMap getLVRank(String[] params)throws Exception{
HashMap rankMap=new HashMap();
String uid = ThaliaCookieMgr.getThaliaCookieValue(FlexContext
.getHttpRequest(), ThaliaCookieMgr.cutePigCookieUser);// 用户ID
if(uid==null||"".equals(uid)){
return errorResult(rankMap);
}
String key="cute_lvrank";
MemCachedClient mcc=MemcachedUtil.getMemCachedClient();
String jsonStr=(String)mcc.get(key);
JSONObject rankResult=null;
if(jsonStr!=null){
rankResult=JSONObject.fromObject(jsonStr);
}
boolean resetCache=false;
if(rankResult==null){
resetCache=true;
}else{
long refreshTime=rankResult.getLong("refreshTime");
long now=System.currentTimeMillis();
if(now-refreshTime>ONE_DAY_MILLI_SECOND){
resetCache=true;
}
}
if(resetCache){
rankResult=getRank();
//mcc.set(key,rankResult,new java.util.Date(Config.getInstance().getMemCachedExpire()));
Date expireDate=new Date(15*60*1000l);
mcc.set(key,rankResult.toString(),expireDate);
}
rankResult=getMyRank(rankResult,uid);
rankMap.put("rankResult", rankResult.toString());
return rankMap;
}
public static JSONObject getMyRank(JSONObject rankResult,String cu_id){
JSONObject myRank=new JSONObject();
Connection conn = null;
Statement pst = null;
ResultSet rs = null;
try {
conn = createConnection();
pst = conn.createStatement();
rs=pst.executeQuery("select CU_RANK from cute_lvrank where cu_uid="+cu_id+";");
while(rs!=null&&rs.next()){
myRank.put("rank",rs.getInt(1));
}
rankResult.put("my_rank",myRank);
} catch (SQLException e) {
e.printStackTrace();
} finally {
destroy(rs,pst,conn);
}
return rankResult;
}
public static synchronized JSONObject getRank()throws Exception{
createLVRank();
JSONObject rankResult=new JSONObject();
JSONArray rankArray=new JSONArray();
Connection conn = null;
PreparedStatement cpst = null;
Statement pst = null;
ResultSet rs = null;
ResultSet res = null;
try {
conn =createConnection();
pst = conn.createStatement();
rs=pst.executeQuery("select CU_RANK,CU_UID,CU_LVNUM from cute_lvrank limit 6;");
String sql = "select count(CU_RANK) from cute_lvrank";
cpst = conn.prepareStatement(sql);
res = cpst.executeQuery();
int total = 0;
if(res.next()){
total = res.getInt(1);
}
while(rs!=null&&rs.next()){
JSONObject rankLine=new JSONObject();
rankLine.put("CU_RANK",rs.getInt(1));
int cu_id=rs.getInt(2);
rankLine.put("CU_UID",cu_id);
rankLine.put("CU_LVNUM",rs.getInt(3));
rankArray.add(rankLine);
}
rankResult.put("top_ranks",rankArray.toArray());
rankResult.put("total", total);
} catch (SQLException e) {
e.printStackTrace();
} finally {
destroy(res,rs,cpst,pst,conn);
}
long time=System.currentTimeMillis();
rankResult.put("refreshTime", time);
rankResult.put("refreshTimeShow", getRefreshTimeStr(getTodayRefreshTime()));
rankResult.put("refreshTimeTrue", getRefreshTimeStr(time));
return rankResult;
}
public static long getTodayRefreshTime(){
java.util.Date now=new java.util.Date();
SimpleDateFormat sd1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
SimpleDateFormat sd2 = new SimpleDateFormat("yyyy-MM-dd");
long milli_seconds=System.currentTimeMillis();
try{
milli_seconds=sd1.parse(sd2.format(now)+" "+RERANK_TIME).getTime();
}catch(Exception e){
}
return milli_seconds;
}
public static String getRefreshTimeStr(long time){
Date date = new Date();
date.setTime(time);
SimpleDateFormat fomatf = new SimpleDateFormat(SourceInternation.changeToOther("public.ymdDateFormat"));
String formatOp = fomatf.format(date);
return formatOp;
}
public static HashMap errorResult(HashMap resultMap){
resultMap.put("ACK", "1");
resultMap.put("ACK_MSG", SourceInternation.changeToOther("public.dataError"));
return resultMap;
}
public static void testProxool(){
ExecutorService exe = Executors.newFixedThreadPool(5000);
Runnable run =null;
for(int i=0;i<100000;i++){
run = new Runnable(){
public void run(){
//int rand = (int)(100*Math.random());
int lvNum = (int)(100000*Math.random());
int uid = (int)(210000*Math.random());
addOrUpdateLvNum(uid,lvNum);
}
};
exe.submit(run);
if(i%10000==0){
System.out.println("proxool test ..."+i);
}
}
exe.shutdown();
}
/**
* @param args
*/
public static void main(String[] args) {
//System.out.println(createConnection());
int id = 2012;
String name = "开心猪仔";
long start = System.currentTimeMillis();
System.out.println("-------开始-------");
/*for(int i=1;i<350000;i++){
lvNum = (int)(10000*Math.random());
//insertCuteLV(i,lvNum);
updateCuteLV(i,0);
//System.out.println(i+"\t-------\t"+updateCuteLV(createConnection(),i,name+i,lvNum));
if(i%10000==0){
System.out.println(i);
}
}*/
java.util.concurrent.ExecutorService exe = java.util.concurrent.Executors.newFixedThreadPool(20);
Runnable run =null;
for(int i=0;i<2000;i++){
run = new Runnable(){
public void run(){
//int rand = (int)(100*Math.random());
int lvNum = (int)(100000*Math.random());
int uid = (int)(210000*Math.random());
addOrUpdateLvNum(uid,lvNum);
}
};
exe.submit(run);
}
exe.shutdown();
//batchInsertCuteLV();
//addOrUpdateLvNum(2012);
/*HashMap map = getLVRank(20009,1,6);
Set set = map.keySet();
Iterator it = set.iterator();
while(it.hasNext()){
String sid = (String)it.next();
System.out.println(sid+"\t"+map.get(sid));
}*/
//System.out.println(System.currentTimeMillis()-getTodayRefreshTime()>3*60*1000);
//System.out.println(System.currentTimeMillis());
//System.out.println(getTodayRefreshTime());
System.out.println((int)(100*Math.random()));
System.out.println((System.currentTimeMillis() - start)/1000+"s");
}
}