java编程之方法模板模型
2019-04-14 18:35发布
生成海报
java编程之方法模板模型
在日常开发过程中,难免遇到相对独立的功能模块的开发,如 监控告警 功能 ,
如何将此部分代码有效的管理起来,保证代码的可读性及易维护性是我们经常需要考虑的问题。 下面为大家介绍一种简单有效的编程模型-
方法模板模型,现以 监控告警 这个功能作为样例,为大家介绍‘方法模板模型’的使用。
- 监控告警功能-方法模板关系模型Visio
- 代码部分
方法模板关系模型Visio
代码部分
由于监控维度较多,以下只以AVG基线监控告警为例
/**
* 监控告警任务上下文
*/
public class TaskContext {
private AlarmConfig ac;
public TaskContext(AlarmConfig alarmConfig){
this.ac = alarmConfig;
}
public TaskContext(){}
public boolean getResult(String message){
return ac.warning(message);
}
public AlarmConfig getAc() {
return ac;
}
public void setAc(AlarmConfig ac) {
this.ac = ac;
}
}
/**
* 监控告警 配置 方法模板
*/
public interface AlarmConfig {
String getType();
String getIntervalTime();
String getConfigJson();
boolean warning(String message);
}
/**
* AVG基线监控配置类:
* @author xiaoxiangxu
*
*/
public class AvgBaseLineConfig implements AlarmConfig{
private String type = AlarmTypeEnum.AVG_BASELINE_LIMIT.getType();
/** 下降百分比*/
private Long threshold;
private int numberOfTimes;
private Integer warningIntervalTime;
private String intervalTime;
private String configJson;
@Override
public String getConfigJson() {
return configJson;
}
public void setConfigJson(String configJson) {
this.configJson = configJson;
}
@Override
public String getType() {
return type;
}
@Override
public boolean warning(String message) {
return false;
}
public AvgBaseLineConfig(LinkedTreeMap map ,QueryServiceImpl queryService) {
List dec = queryService.queryAllEmergencyConfigModel();
if(map!=null && map.size() > 0){
NumberFormat formatter = new DecimalFormat("0");
this.setThreshold(Long.parseLong(formatter.format(map.get("threshold"))));
this.setNumberOfTimes(ParmsUtils.getSafeValue_Integer(formatter.format(map.get("numberOfTimes"))));
this.setIntervalTime((String) map.get("intervalTime"));
this.setConfigJson((String)map.get("configJson"));
}
if(dec!=null && dec.size() >0) {
EmergencyDefaultConfigModel config = dec.get(0);
if (!StringUtil.isEmpty(config.getDefultConfigJson())) {
String jsonParm = config.getDefultConfigJson().trim();
WarningDefaultConfigJsonBean depts = new Gson().fromJson(jsonParm, WarningDefaultConfigJsonBean.class);
this.setWarningIntervalTime(depts.getAvgBaseLineConfig().getWarningIntervalTime());
}
}
}
public AvgBaseLineConfig(WarningDefaultConfigJsonBean.AvgBaseLineConfig_ t) {
this.setConfigJson(t.getConfigJson());
this.setIntervalTime(t.getIntervalTime());
this.setWarningIntervalTime(t.getWarningIntervalTime());
this.setThreshold(NumberUtil.toLong(String.valueOf(t.getThreshold())));
this.setNumberOfTimes(t.getNumberOfTimes());
}
public void setType(String type) {
this.type = type;
}
public long getThreshold() {
return threshold;
}
public void setThreshold(long threshold) {
this.threshold = threshold;
}
public int getNumberOfTimes() {
return numberOfTimes;
}
public void setNumberOfTimes(int numberOfTimes) {
this.numberOfTimes = numberOfTimes;
}
public Integer getWarningIntervalTime() {
return warningIntervalTime;
}
public void setWarningIntervalTime(Integer warningIntervalTime) {
this.warningIntervalTime = warningIntervalTime;
}
@Override
public String getIntervalTime() {
return intervalTime;
}
public void setIntervalTime(String intervalTime) {
this.intervalTime = intervalTime;
}
public AvgBaseLineConfig() {}
}
/**
* Created by xiaoxiangxu on 2015/12/14.
*/
@Component
public abstract class AlarmTaskTemplate {
private static final Logger LOG = new Logger(AlarmTaskTemplate.class);
public static final int DEFAULT_BATCH_SIZE = 1;
private String CQL_RESULT_QUERY = "select b_content from test.baseline_result where b_id='_KEY'";
@Resource
protected CacheDomain cacheDomain;
@Resource
protected SearchDomain searchDomain;
@Resource
protected CacheClient cacheClient;
@Resource
protected QueryServiceImpl queryService;
protected ReadWriteLock lock = new ReentrantReadWriteLock(false);
private String warningKey = "";
private AlarmTaskModel tm ;
private Long startTime;
private Long endTime;
private List dec;
/**
* 过滤满足条件的监控数据
* @param taskModelList
* @param interval
*/
protected abstract boolean toWarning(List taskModelList,String interval);
/**
* 告警信息
* @param
* @param config
* @param yearMonthIndex
* @param searchModel
* @return
*/
protected abstract String getAlarmMessage(Object config, String yearMonthIndex, SearchModel searchModel) ;
/**
* 获取基线key
* @param
* @param key
* @return
*/
protected abstract String getBaselineKey(String key) ;
/**
* 开始执行JOB
* @param scheduleContext
* @return
* @throws Exception
*/
public String getIntervalTime(ScheduleContext scheduleContext) throws Exception {
return scheduleContext.getTaskGetResponse().getParameter().get("interval");
}
/**
* 根据type获取默认告警时间间隔,默认1分钟
* @param type
* @return
*/
public int getDefaultIntervalTime(String type){
if(dec==null || dec.size() ==0) {
dec = queryService.queryAllEmergencyConfigModel();
}
try {
Validate.notEmpty(dec, "warning : warningDefaultConfig has not config , please config default config as soon as possible !");
EmergencyDefaultConfigModel config = dec.get(0);
if (!StringUtil.isEmpty(config.getDefultConfigJson())) {
WarningDefaultConfigJsonBean depts = new Gson().fromJson(config.getDefultConfigJson().trim(), WarningDefaultConfigJsonBean.class);
if (type.equals(AlarmTypeEnum.FAILURES.getType())) {
return depts.getFailuresConfig().getWarningIntervalTime();
} else if (type.equals(AlarmTypeEnum.AVG_BASELINE_LIMIT.getType())) {
return depts.getAvgBaseLineConfig().getWarningIntervalTime();
} else if (type.equals(AlarmTypeEnum.AVG_TIME.getType())) {
return depts.getAvgTimeConfig().getWarningIntervalTime();
} else if (type.equals(AlarmTypeEnum.LOWERLIMIT_MONITOR.getType())) {
return depts.getLowerLimitConfig().getWarningIntervalTime();
} else if (type.equals(AlarmTypeEnum.RET_CODE_MONITOR.getType())) {
return depts.getRetCodeConfig().getWarningIntervalTime();
} else if (type.equals(AlarmTypeEnum.TIME_OUT.getType())) {
return depts.getTimeOutConfig().getWarningIntervalTime();
} else if (type.equals(AlarmTypeEnum.TP_MONITOR.getType())) {
return depts.getTpConfig().getWarningIntervalTime();
} else if (type.equals(AlarmTypeEnum.TPS_BASELINE_LIMIT.getType())) {
return depts.getTpsBaseLineConfig().getWarningIntervalTime();
}
}
}catch (Exception e){
LOG.error(e.getMessage());
return 1;
}
return 1;
}
/**
* ES 查询条件
* @param att
* @return
*/
protected SearchModel searchModel(AlarmTaskTemplate att){
try {
SearchModel searchModel = new SearchModel();
if (att != null) {
searchModel.setStartTime(att.getStartTime());
searchModel.setEndTime(att.getEndTime());
searchModel.setAppName(att.getTm().getAppName());
searchModel.setServiceName(att.getTm().getServiceName());
searchModel.setMethodName(att.getTm().getMethodName());
}
return searchModel;
}catch (Exception e){
LOG.error("CacheDomain saveWarningInterval() error : ", e);
return null;
}
}
/**
* 获取配制的监控数据列表
* @return
*/
protected List getTaskModelList(String interval){
List taskModelList= null;
if(isEmpty(interval)) {
taskModelList = searchDomain.queryAllAlarmTaskModel();
}else {
AlarmTaskModel alarmTaskModel = new AlarmTaskModel();
alarmTaskModel.setCronExpression(interval);
taskModelList = searchDomain.queryAlarmTaskModelByInterval(alarmTaskModel);
}
return taskModelList==null?new ArrayList():setOtherInfo(taskModelList);
}
/**
* 按KEY获取应用基线数据
* @return
*/
public Map> getBaseLineByKey(String key){
LOG.info("按KEY获取应用基线数据" ,key);
Validate.notEmpty(key, "key is empty");
return searchDomain.searchBaselineByKey(key, CQL_RESULT_QUERY.replace("_KEY",getBaselineKey(key)));
}
/**
* 增加告警邮箱与手机号
* @param taskModelList
* @return
*/
protected List setOtherInfo(List taskModelList){
DepartmentOrApp departmentOrApp = null;
try {
for (AlarmTaskModel alarmTaskModel : taskModelList) {
Set alarmMobiles = new HashSet();
Set alarmEmails = new HashSet();
if (alarmTaskModel == null || StringUtil.isEmpty(alarmTaskModel.getAppName())) {
continue;
}
alarmMobiles = StringUtil.isEmpty(alarmTaskModel.getMobiles())?new HashSet():new HashSet(Arrays.asList(alarmTaskModel.getMobiles().split(",")));
departmentOrApp = searchDomain.getAppCenterInfo(alarmTaskModel.getAppName());
if (departmentOrApp == null || departmentOrApp.getUser() == null) {
continue;
}
for (AlamUser alamUser : departmentOrApp.getUser()) {
alarmMobiles.add(alamUser.getPhone());
alarmEmails.add(alamUser.getMail());
}
for(String defaultEmailAddress : Constant.BASELINE_DEFAULT_EMAIL_ADDRESS.split(",")){
alarmEmails.add(defaultEmailAddress);
}
alarmTaskModel.setMobiles(new Gson().toJson(alarmMobiles));
alarmTaskModel.setEmails(new Gson().toJson(getWarningEmailAddressByMobileFromCache(alarmMobiles,alarmEmails)));
}
}catch (Exception e){
LOG.error("setOtherInfo error : ",e);
}
return taskModelList;
}
/**
* 通过告警手机号,查询缓存中对应的email地址
* @param alarmMobiles
* @param alarmEmails
*/
public Set getWarningEmailAddressByMobileFromCache(Set alarmMobiles,Set alarmEmails){
if(alarmMobiles==null){
return alarmMobiles;
}
try{
Map userModelMap = (Map) cacheClient.getObjcet(Constant.LDAP_USER_INFO_CACHE);
if(userModelMap!=null){
Set> set = userModelMap.entrySet();
for(Map.Entry entry : set){
alarmEmails.add(entry.getValue().getMail());
}
}
}catch (Exception e){
LOG.error("getWarningEmailAddressByMobileFromCache error :",e);
}
return alarmEmails;
}
/**
* 获取当前数据
* @param app
*/
protected Map getPonitFromCassandraByKey(String type,String app,AlarmTaskTemplate template){
Map map = new HashMap();
try {
List>> result = searchDomain.getAppDataForWarning(app,type, cacheClient.getData(template.getWarningKey()), TimeUtils.getNowDay());
if (result == null || result.size() == 0) {
return map;
}
for (int i = 0; i < result.size(); i++) {
List
到此 方法模板模型 样例介绍结束,代码量比较大未做过多删减,希望大家能够感受其中精妙之处。
打开微信“扫一扫”,打开网页后点击屏幕右上角分享按钮