Strategy 角色 User 源代码:
package com.defonds.mysql.user;
public interface User {
// 策略模式的应用:把具体做法让每个 User 分别封装起来,做法独立于调用 User 的 thread
public void doMyThing();
}
ConcreteStrategy 角色之一 RawAddUser 源代码:
package com.defonds.mysql.user.raw;
import com.defonds.mysql.raw.service.RawService;
import com.defonds.mysql.user.User;
public class RawAddUser implements User {
private RawService rawService;
private int numCountor = 1; // 记录次数
public void setRawService(RawService rawService) {
this.rawService = rawService;
}
@Override
public void doMyThing() {
long uid = 111;
long did = 1111;
long fileId = 11111;
long sectionId = 111111;
long startTime = System.currentTimeMillis();
String s3RawHeaderPath = "/usr/home/df/wefd.txt" + numCountor;
String channelId = "1";
if (numCountor >= 20) {
numCountor = 1;
}
uid += numCountor;
did += numCountor;
fileId += numCountor;
sectionId += numCountor;
rawService.addTimeLineRaw(uid, did, fileId, sectionId, startTime, startTime + 15000, s3RawHeaderPath, channelId);
numCountor ++;
}
}
Context 角色 Runner 源代码:
package com.defonds.mysql.runner;
import java.util.Date;
import com.defonds.mysql.user.User;
import com.defonds.mysql.util.dao.RecordDao;
public abstract class Runner implements Runnable {
protected RecordDao recordDao;
protected User user;
protected String sceneDesc;
protected String type;
protected String requestDesc;
protected long interval;
public void setRecordDao(RecordDao recordDao) {
this.recordDao = recordDao;
}
public void setUser(User user) {
this.user = user;
}
/**
*
* @param sceneDesc // 场景名
* @param type // 操作类型 [insert、delete、update、select]
* @param requestDesc // 对应 timeline.xml 文件中的语句 id
* @param interval // 两次执行之间的时间间隔
*/
public Runner(String sceneDesc, String type, String requestDesc, long interval) {
this.sceneDesc = sceneDesc;
this.type = type;
this.requestDesc = requestDesc;
this.interval = interval;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(this.interval);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Date startTime = new Date();
long startTimeL = System.currentTimeMillis();
this.user.doMyThing();
Date endTime = new Date();
long endTimeL = System.currentTimeMillis();
this.record(this.sceneDesc, this.type, startTime, endTime, endTimeL - startTimeL, this.requestDesc, null);
}
}
protected void record(String sceneDesc, String type, Date startTime, Date endTime, long extendTime, String requestDesc, String requestDetail) {
this.recordDao.addRecord(sceneDesc, type, startTime, endTime, extendTime, requestDesc, requestDetail);
}
}