一、多敲出来的代码
为了解析对方传过来的多种不同格式的监测数据,首先想到的是使用策略模式实现根据参数tablename进行区分进入不同的处理。写之前觉得自己想的老好了,不同的参数类型组成的json对应不同的实体类,实体类注解实现字段说明拼接,真不戳!写一半,对方搞得实体类越来越多,烦死了,真想怒砸键盘!
重新想了下,我直接判断参数类型进行不同处理不就完了,yml配置一下字段说明的对应,省事多了,又白敲了一大片,吐血!记录一下自己多敲出来的代码,万一以后有用呢!
二、具体实现自定义注解策略模式
1.自定义一个注解
package mon.ano;
import org.springframework.stereotype.Service;
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Service
public @interface Monitor {
//用于分类的tableName
String tableName();
}
2.写一个实现类(策略类)
package mon.serviceImpl;
import mon.ano.Monitor;
import mon.service.HandleInterface;
//标识为AAA的实现
@Monitor(tableName = "AAA")
public class handleServiceImpl implements HandleInterface {
@Override
public void getData(String json) {
System.out.println("解析中。。。");
}
}
3.重写setReportTaskBusinessLogicMap()实现策略类读取
不用手写一个个判断了,记得以前实现过,这次写忘了,又找了好久,决定这次写下来
package mon.service;
import mon.ano.Monitor;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class HandleService {
private Map<String, HandleInterface> handleMap = new HashMap<>();
static Logger logger = Logger.getLogger(HandleService.class);
@Autowired
public void setReportTaskBusinessLogicMap(List<HandleInterface> handleInterfaces) {
handleMap = handleInterfaces.stream().collect(Collectors.toMap(t -> AnnotationUtils.findAnnotation(t.getClass(), Monitor.class).tableName(), v -> v, (v1, v2) -> v1));
// for (HandleInterface t : handleInterfaces) {
// handleMap.put(AnnotationUtils.findAnnotation(t.getClass(), Monitor.class).tableName(), t);
// }
}
public void handle(String json) throws Exception {
//可以根据注解的值判断走哪个实现类,如果有多个实现类就会依次走
JSONObject jsonObject = JSONObject.parseObject(json);
String key = jsonObject.getString("tableName");
handleMap.entrySet().forEach(entry -> {
if (entry.getKey().contains(key)) {
HandleInterface handlein = handleMap.get(entry.getKey());
handlein.getData(json);
} else {
logger.error("Error:This changeTablename " + key + " does not exists!");
}
});
// JSONObject jsonObject = JSONObject.parseObject(json);
// String key = jsonObject.getString("tableName");
// int flag = 0;
// for (Map.Entry<String, HandleInterface> entry : handleMap.entrySet()) {
// if (entry.getKey().contains(key)) {
// HandleInterface handlein = handleMap.get(entry.getKey());
// handlein.getData(json);
// } else {
// flag++;
// }
// }
// if (flag == handleMap.size()) {
// logger.error("Error:This Tablename " + key + " does not exists!");
// throw new Exception("Error:This tablename " + key + " does not exists!");
// }
}
}
大体上就是这么实现的,跑完测试没啥问题,具体各种策略类实现写一半就疯了,太多了放弃了。至于通过判断参数类型的方法,等写完了再记录。