Spring中的事件监听机制在项目中的应用

来源:互联网 发布:linux 终端快捷键 编辑:程序博客网 时间:2024/05/21 05:05

最经在做项目的时候,调用某个接口的时候为了调用地图,而不希望因为调用超时影响到主线程,使用了spring的时间监听机制。

Spring中提供一些Aware相关的接口,BeanFactoryAware、 ApplicationContextAware、ResourceLoaderAware、ServletContextAware等等,其中最常用到的是ApplicationContextAware。实现ApplicationContextAware的Bean,在Bean被初始后,将会被注入ApplicationContext的实例。ApplicationContextAware提供了publishEvent()方法,实现Observer(观察者)设计模式的事件传播机,提供了针对Bean的事件传播功能。通过Application.publishEvent方法,我们可以将事件通知系统内所有的ApplicationListener。

Spring事件处理一般过程:

◆定义Event类,继承org.springframework.context.ApplicationEvent。
◆编写发布事件类Publisher,实现org.springframework.context.ApplicationContextAware接口。
◆覆盖方法setApplicationContext(ApplicationContext applicationContext)和发布方法publish(Object obj)。
◆定义时间监听类EventListener,实现ApplicationListener接口,实现方法onApplicationEvent(ApplicationEvent event)。

项目中的伪代码

  1. 定义Event类,继承org.springframework.context.ApplicationEvent。
  public class Gis0002SuccessEvent extends ApplicationEvent{    /**      * <B>Summary:</B> <Br>       * serialVersionUID:TODO(用一句话描述这个变量表示什么) <Br>       *      * @since Ver @version      */        private static final long   serialVersionUID    = 1L;    public Gis0002SuccessEvent ( GiS0002 source )    {          super ( source );    }}

2.编写发布事件类Publisher,实现org.springframework.context.ApplicationContextAware接口。
3.覆盖方法setApplicationContext(ApplicationContext applicationContext)和发布方法publish(Object obj)。

public class AgA01003ServiceImpl implements AgA01003Service,ApplicationContextAware{    //把救援人的信息传给地图  2015.07.21    public void dealMapMoniter(AgA01003Entity aga01003Entity){        GiS0002 giS0002 = new GiS0002();        log.info("--救援监控救援人信息数据---"+JsonUtil.toJSONString ( aga01003Entity ));        /******************以下是处理工单服务人员信息数据  begin*****************************/        giS0002.setTicketID  ( aga01003Entity.getTicketID ( ) );//工单编号        giS0002.setRescueName  ( aga01003Entity.getRescueName ( ) );//救援人员名称        giS0002.setRescuePhone  ( aga01003Entity.getRescuePhone ( ) );//救援人员电话        //giS0002.setRealServiceType( aga01003Entity.getServiceCode ( ) );//服务项目代码        //设置服务中文名称 edit by zhaolei 2015-08-03        String serviceName = sendMessageService.getSpTypeMateDataNameByCode(aga01003Entity.getServiceCode ( ));        giS0002.setRealServiceType( serviceName );//服务项目代码        giS0002.setRescueLatitude  ( aga01003Entity.getCaseLatitude ( ) );        giS0002.setRescueLongitude ( aga01003Entity.getCaseLongitude ( ) );        giS0002.setRescueVehicleNo  ( aga01003Entity.getRescueVehicleNo ( ) );//车牌号        //因调用地图时,如超时,会影响到主流程,所以改为监听 2015.08.10        this.ac.publishEvent ( new Gis0002SuccessEvent ( giS0002 ) );    }}

定义时间监听类EventListener,实现ApplicationListener接口,实现方法onApplicationEvent(ApplicationEvent event)。

public class Gis0002Listener implements SmartApplicationListener{    Logger log = LoggerFactory.getLogger ( Gis0002Listener.class );    @Resource( name = "dictionaryService" )    private DictionaryService           dictionaryService;    @Resource(name="logManagerSerivce")    private LogManagerSerivceImpl logManageService;    @Override    @Async //配置成异步处理数据    public void onApplicationEvent ( ApplicationEvent arg0 )    {        GiS0002  giS0002 = (GiS0002)arg0.getSource ( );        Enum enums = dictionaryService.searchByCode (   InitSpring.getMessage ( "RUNTIMEENUM" ) ,                "monitorRescue" );            //从配置库中取得接口url        String urlName = enums.getName ( );        log.info("救援监控救援人信息接口="+urlName);        JacksonJsonSimpleMarshaller sm = new JacksonJsonSimpleMarshaller ( );        String resJson = sm.marshaller ( giS0002 ,new ByteArrayOutputStream ( ) );        log.info("救援监控救援人信息请求参数="+resJson);        List<NameValuePair> json =  new ArrayList<NameValuePair> ( );        json.add ( new BasicNameValuePair ( "RequestBodyJson" , resJson ) );        try        {            //调用救援缄口地图            String returnData = HttpUtils.httpPost (urlName , json );            log.info("救援监控救援人信息接口返回="+JsonUtil.toJSONString ( returnData ));            if( returnData.matches ( ".*404.*" ) ){                logManageService.saveLog ( giS0002 , returnData ,"" ,                                              "", giS0002.getTicketID ( ) ,                                                "1" , Contants.GiS0002 );            }        }        catch ( HttpHostConnectException e )        {              log.error ( e.getMessage ( ) );              logManageService.saveLog ( giS0002 , "" ,e.getMessage ( ) ,                                          "", giS0002.getTicketID ( ) ,                                            "1" , Contants.GiS0002 );        }    }    @Override    public int getOrder ( )    {          return 1;    }    @Override    public boolean supportsEventType ( Class<? extends ApplicationEvent> eventType )    {          return eventType == Gis0002SuccessEvent.class;    }    @Override    public boolean supportsSourceType ( Class<?> sourceType )    {          return sourceType ==GiS0002.class;    }}
0 0
原创粉丝点击