Spring中的ApplicationListener的使用详解案例(观察者模式)

10 篇文章 0 订阅
10 篇文章 0 订阅

一、前言

        ApplicationListener是Spring事件机制的一部分,与抽象类ApplicationEvent类配合来完成ApplicationContext的事件机制。

        如果容器中存在ApplicationListener的Bean,当ApplicationContext调用publishEvent方法时,对应的Bean会被触发。这一过程是典型的观察者模式的实现。

一、目的

        在开发过程中,需要涉及跨平台数据推送,因此使用自定义事件。

二、ApplicationListener源码

@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
    void onApplicationEvent(E var1);

    static <T> ApplicationListener<PayloadApplicationEvent<T>> forPayload(Consumer<T> consumer) {
        return (event) -> {
            consumer.accept(event.getPayload());
        };
    }
}

三、项目代码实现

1.所需的maven包

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.18</version>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-http</artifactId>
            <version>5.7.4</version>
        </dependency>
    </dependencies>

2.自定义事件及监听

@Getter
public class PushEvent extends ApplicationEvent {

    private IPushData.PushDataType dataType;

    public PushEvent(PushTask pushTask, IPushData.PushDataType dataType){
        super(pushTask);
        this.dataType = dataType;
    }
}


@Slf4j
@Component
public class PushEventListener implements ApplicationListener<PushEvent> {
    @Override
    public void onApplicationEvent(PushEvent pushEvent) {
        PushTask pushTask = (PushTask) pushEvent.getSource();
        final String data = pushTask.getPushData();
        final String url = "http://192.168.169.218:8080/pushEvent";
        //3.发送数据
        String result = null;
        try {
            result = HttpUtil.createPost(url)
                    .body(String.format("data=%s", data))
                    .execute()
                    .body();
            recordSuccessTime("推送成功");
        } catch (Throwable t) {
            log.error("推送数据异常——>", t);
            result = t.getMessage();
        } finally {
            log.info("Push task execution -> type:{}  | to : {} | result : {} | data : {}", pushEvent.getDataType(), url, result, data);
        }
    }

    /**
     * 记录成功信息
     *
     */
    private void recordSuccessTime(String message) {
        System.out.println(message);
    }
    
}

3.Controller层代码

@Controller
public class HelloController {

    @Resource
    OrgPushPublisher orgPushPublisher;

    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
        orgPushPublisher.pushCreateEvent(new OrgSynchronizationIncrementDTO("1","北京办事处"));
        return "Hello World!";
    }

    @ResponseBody
    @RequestMapping("/pushEvent")
    public String pushEvent(String data){
        System.out.println("接收到的数据data="+data);
        return "接收成功";
    }
}

4.访问地址

        http://localhost:8080/hello

5.执行结果

 

6.项目链接

        https://gitee.com/chaoren_me/ApplicationListenerDemo.git

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值