原来的代码逻辑:
@Component
@Slf4j
@JobHandler(value = "wechatSettlementHandler")
public class WechatSettlementHandler extends IJobHandler {
@Autowired
private SettlementBatchResource settlementBatchResource;
@Override
public ReturnT<String> execute(String s) throws Exception {
if(StringUtils.isEmpty(s)){
log.info("执行时间: {}", DateTime.now());
settlementBatchResource.weChatApproveBatch(DateTime.now().withTimeAtStartOfDay().getMillis());
return SUCCESS;
}
try{
Date date = new SimpleDateFormat("yyyyMMdd").parse(s);
log.info("执行时间: {}", date);
settlementBatchResource.weChatApproveBatch(date.getTime());
}catch (Exception e){
log.error("时间解析失败: {}", e);
}
return SUCCESS;
}
}
问题:每次新增一个Job都要写很多重复的代码,所以希望将这部分公共代码抽取出来。
代码优化:
1)通过JobUtils类将公共代码抽取
@Slf4j
public class JobUtils {
public static void doJob(Consumer consumer, String s){
if(StringUtils.isEmpty(s)){
log.info("执行时间: {}", DateTime.now());
long batchDate = DateTime.now().withTimeAtStartOfDay().getMillis();
consumer.accept(batchDate);
}
try{
Date date = new SimpleDateFormat("yyyyMMdd").parse(s);
log.info("执行时间: {}", date);
consumer.accept(date.getTime());
}catch (Exception e){
log.error("时间解析失败: {}", e);
}
}
}
2)原先的代码逻辑变得很简单
@Component
@Slf4j
@JobHandler(value = "wechatSettlementHandler")
public class WechatSettlementHandler extends IJobHandler {
@Autowired
private SettlementBatchResource settlementBatchResource;
Consumer<Long> consumer = new Consumer<Long>() {
@Override
public void accept(Long batchDate) {
settlementBatchResource.weChatApproveBatch(batchDate);
}
};
@Override
public ReturnT<String> execute(String s) throws Exception {
JobUtils.doJob(consumer, s);
return SUCCESS;
}
}
使用lambda方式让代码更加简洁:
@Component
@Slf4j
@JobHandler(value = "wechatSettlementHandler")
public class WechatSettlementHandler extends IJobHandler {
@Autowired
private SettlementBatchResource settlementBatchResource;
Consumer<Long> consumer = batchDate -> settlementBatchResource.weChatApproveBatch(batchDate);
@Override
public ReturnT<String> execute(String s) throws Exception {
JobUtils.doJob(consumer, s);
return SUCCESS;
}
}
返回集合中的一条数据:
@Data
public static class ResultBean {
private String startDate;
private String updatedDate;
private String personScope;
private List<ARContactListBean> aRContactList;
}
Optional.ofNullable(qygsxxhy.getResult()).map(e -> {
//这边要加一条判断
if(CollectionUtils.isEmpty(e.getARContactList())){
return null;
}
return e.getARContactList().get(0);
}).orElse(null)