listener,filter区别--ZT

本文详细解释了Filter(过滤器)和Listener(监听器)的区别与联系。Filter主要用于处理请求前后的过滤工作,如权限控制、乱码处理等;而Listener则用于监听应用中的特定事件,如session创建和销毁等。


web.xml里面可以配置Filter和Listener,他们有什么区别,有什么共同点吗?应该在什么情况下使用他们?
网友回复:Filter是过滤器,过滤一些不友好或是你不想要的东东, 

Listener是Servlet的监听器,可以监听客户端的请求、服务端的操作等。 
通过监听器,可以自动激发一些操作。
网友回复:Filter可以实现对请求的过滤和重定向等,也就是说可以操作request和response,session等对象,listner只能监听到以上对象的属性的修改。
网友回复:Filter 是struts的核心控制器,负责拦截所有用户请求。 
listener是监听器,通常都是监听并加载一些插件用的,比如spring。log4j等
网友回复:Filter(过滤器):你可以写个类实现Filter接口,然后配置到web.xml中,那么Tomcat在接受到Http请求后首先会调用FilterChain中的第一个过滤器,为了能调用下个过滤器或真正的请求(servlet or jsp),所以你的实现类所实现的方法中必须要调用chain.doFilter(request,response),不然会得到空白页面!过滤器通常用做处理乱码,权限控制,也可以治理Hibernate中的session! 
Listener(监听器):利用观察者模式实现,在Tomcat中,假如要对application,session,request,response等对象监听,要实现类似****Listener接口,再配置到web.xml中,那么Tomcat在启动的时候就会把你写的这些监听类实例化成对象加入到一个集合中,此后对你要监听的对象操作时,都将会调用listener中的方法,比如HttpSessionListener 可以用来监听当前在线的所有用户!
网友回复:Filter和servlet基本类似 可以用做servlet来用(struts2.0就是这么干的) 有reqeust请求才能运行 

listener是监听器 是系统启动就运行 一般监听都是用来事先加载系统文件的
网友回复:
Filter是过滤器,过滤一些不友好或是你不想要的东东, 

Listener是Servlet的监听器,可以监听客户端的请求、服务端的操作等。 
通过监听器,可以自动激发一些操作。 

也是我地看法
网友回复:本身从字面上都比较好理解区分的 
Filter 过滤器, 

Listener 监听器

package com.jsfj.evcall.biz.task.listener; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollectionUtil; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.toolkit.BeanUtils; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.jsfj.common.util.RedisUtil; import com.jsfj.evcall.biz.common.conf.TaskEmergencyConfig; import com.jsfj.evcall.biz.common.constants.task.CarOutStatusEnum; import com.jsfj.evcall.biz.common.util.HttpUtils; import com.jsfj.evcall.biz.task.dao.mapper.ICarOutMapper; import com.jsfj.evcall.biz.task.entity.DispatchInfoDto; import com.jsfj.evcall.biz.task.entity.po.CarOutPo; import com.jsfj.evcall.biz.task.event.DispatchTimeNodeEvent; import com.jsfj.evcall.biz.task.push.CarOutInfoDto; import com.jsfj.evcall.biz.unit.dao.mapper.IAmbMapper; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.ApplicationListener; import org.springframework.data.redis.connection.RedisServer; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.*; import java.util.stream.Collectors; /** * 推送调度信息 */ @Component @Async @Slf4j @ConditionalOnProperty(prefix = "push.suining", name = "enable", havingValue = "true", matchIfMissing = false) public class DispatchTimeNodeEventListener implements ApplicationListener<DispatchTimeNodeEvent> { @Autowired private ICarOutMapper iCarOutMapper; @Autowired private IAmbMapper iAmbMapper; @Autowired private RedisUtil redisUtil; @Autowired private TaskEmergencyConfig taskEmergencyConfig; @Override public void onApplicationEvent(DispatchTimeNodeEvent event) { //获取调度id DispatchInfoDto dto = (DispatchInfoDto) event.getSource(); Long dispatchId = dto.getDispatchId(); log.info("接受到的参数:{}", dispatchId); //查询调度出车信息 List<CarOutPo> carOutPos = iCarOutMapper.selectList(Wrappers.<CarOutPo>lambdaQuery().eq(CarOutPo::getTaskDispatchId, dispatchId)); if (CollectionUtil.isEmpty(carOutPos)) { return; } List<Integer> carOutStatus = CarOutStatusEnum.pushSH(); //过滤满足条件的出车状态 carOutPos = carOutPos.stream().filter(carOut -> carOutStatus.contains(carOut.getStatus()) || CarOutStatusEnum.isCancel(carOut.getStatus())).collect(Collectors.toList()); //不过滤状态,保证当前状态下有值,时间有值,及时补偿,redis只保存推送成功的 List<CarOutPo> newCarOut = new ArrayList<>(); //判断该阶段是否已经推送过数据 for (CarOutPo carOutPo : carOutPos) { //组装redisKey String redisKey = String.format("PushNode:%s:%s", dispatchId, carOutPo.getAmbId()); List<Integer> status = (List<Integer>) redisUtil.get(redisKey); log.info("redis缓冲的数据:{}",JSONArray.toJSONString(status)); if (CollectionUtils.isEmpty(status) || !status.contains(carOutPo.getStatus())) { log.info("节点状态:{},{}",dispatchId,status); List<Integer> integers = status == null ? new ArrayList<>() : status; integers.add(carOutPo.getStatus()); redisUtil.set(redisKey, integers, 24 * 60 * 60 * 2); newCarOut.add(carOutPo); } // 判断是否是最后一个节点:做补偿机制 if (Objects.equals(carOutPo.getStatus(), CarOutStatusEnum.CAR_ARRIVED_HOSPITAL.getCode())) { log.info("是否进入补偿机制"); List<Integer> pushSH = CarOutStatusEnum.pushSH(); List<Integer> redisStatus = (List<Integer>) redisUtil.get(redisKey); log.info("进入缓冲机制的redis里面的数据:{}",JSONArray.toJSONString(redisStatus)); pushSH.removeAll(redisStatus); log.info("需要补偿的节点数据:{}",JSONArray.toJSONString(pushSH)); if(CollectionUtil.isNotEmpty(pushSH)){ for (Integer zt : pushSH) { CarOutPo carOutPo1 = BeanUtil.copyProperties(carOutPo, CarOutPo.class); log.info("补偿节点状态:{},{}",dispatchId,zt); List<Integer> integers = new ArrayList<>(redisStatus); integers.add(zt); redisUtil.set(redisKey, integers, 24 * 60 * 60 * 2); carOutPo1.setStatus(zt); newCarOut.add(carOutPo1); } } } } if (CollectionUtil.isEmpty(newCarOut)) { return; } List<CarOutPo> collect = newCarOut.stream().sorted(Comparator.comparing(CarOutPo::getStatus)).collect(Collectors.toList()); collect.forEach(carOutPo -> { CarOutInfoDto build = CarOutInfoDto.builder() .jz_dddh(dispatchId.toString()) .ztdm(Optional.ofNullable(carOutPo.getAmbId()).map(Object::toString).orElse(null)) .ztpz(Optional.ofNullable(carOutPo.getPlateNumber()).filter(StringUtils::isNotBlank).orElse(null)) // .czsj(Optional.ofNullable(carOutPo.getLeaveTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)) // .ddxcsj(Optional.ofNullable(carOutPo.getArriveTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)) // .jzhzsj(null) // .fcsj(Optional.ofNullable(carOutPo.getReturnTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)) // .rwwcsj(Optional.ofNullable(carOutPo.getCompletedTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)) // .sfzcjs(carOutPo.getCompletedTime() != null ? 1 : 0) .jdmc(Optional.ofNullable(carOutPo.getStatus()).map(CarOutStatusEnum::carOutStatusName).orElse(null)) .ycyy(Optional.ofNullable(carOutPo.getCancelReason()).filter(StringUtils::isNotBlank).orElse(null)).build(); if (carOutPo.getStatus() != null) { if (Objects.equals(carOutPo.getStatus(), CarOutStatusEnum.CAR_DEPARTED.getCode())) { build.setJlsj(Optional.ofNullable(carOutPo.getLeaveTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)); } else if (Objects.equals(carOutPo.getStatus(), CarOutStatusEnum.CAR_ARRIVED_SITE.getCode())) { build.setJlsj(Optional.ofNullable(carOutPo.getArriveTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)); } else if (Objects.equals(carOutPo.getStatus(), CarOutStatusEnum.CAR_RETURN.getCode())) { build.setJlsj(Optional.ofNullable(carOutPo.getReturnTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)); } else if (Objects.equals(carOutPo.getStatus(), CarOutStatusEnum.CAR_ARRIVED_HOSPITAL.getCode())) { build.setJlsj(Optional.ofNullable(carOutPo.getCompletedTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)); } else if (CarOutStatusEnum.isCancel(carOutPo.getStatus())) { build.setJlsj(Optional.ofNullable(carOutPo.getCancelTime()).map(item-> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)); } } String param = JSONObject.toJSONString(build); retryPush( param,dispatchId); }); } private static final int MAX_RETRIES = 3; private static final long RETRY_INTERVAL_MS = 1000; // 每次重试间隔1秒 public boolean retryPush( String param,Long dispatchId) { int attempt = 0; while (attempt < MAX_RETRIES) { try { if (executePush(param,dispatchId)) { return true; // 推送成功,直接返回 } } catch (Exception e) { log.warn("推送失败(第{}次尝试): {}", attempt + 1, e.getMessage()); } attempt++; if (attempt < MAX_RETRIES) { try { Thread.sleep(RETRY_INTERVAL_MS); // 等待一段时间后重试 } catch (InterruptedException ie) { Thread.currentThread().interrupt(); log.error("线程中断:{}", ie.getMessage()); } } } return false; // 所有重试均失败 } private boolean executePush(String param,Long dispatchId) { log.info("推送的参数:{}", param); log.info("推送地址:{}", taskEmergencyConfig.getBaseUrl() + taskEmergencyConfig.getPushDispatchInfoUrl()); log.info("推送header参数:{}", taskEmergencyConfig.getThirdInstitutionID()); String resultJson = HttpUtils.sendHttps(taskEmergencyConfig.getBaseUrl() + taskEmergencyConfig.getPushDispatchInfoUrl(), taskEmergencyConfig.getThirdInstitutionID(), param); log.info("响应数据:{}", resultJson); if (StringUtils.isNotBlank(resultJson)) { JSONObject jsonObject = JSONObject.parseObject(resultJson); if (!Objects.equals(jsonObject.getString("resultcode"), "0")) { log.error("响应错误提示:{}", jsonObject.getString("message")); //失败的要贴出并补偿 //并将发送数据存入redis中做备份 String key = String.format("TimeNode:%s", dispatchId); redisUtil.set(key, param); return false; } return true; } return false; } } 以上为源代码,根据源代码优化为CAR_DEPARTED ,CAR_DEPARTED,CAR_RETURN,CAR_ARRIVED_HOSPITAL 有序发送, retryPush失败不存redis
05-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值