栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring 事件订阅发布 demo 并实现异步处理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring 事件订阅发布 demo 并实现异步处理

先创建 一个事件

package com.example.jpademo;
import org.springframework.context.ApplicationEvent;

public class Event_A extends ApplicationEvent {

    public Event_A(Object source) {
        super(source);
    }
}

 创建 一个事件监听器

package com.example.jpademo;

import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;


@Component
@EnableAsync // 开启异步处理
public class ApplicationListener_A implements ApplicationListener {

    @Async // 开启异步处理
    @Override
    public void onApplicationEvent(Event_A a) {
        System.out.println("线程名称 " + Thread.currentThread().getName());
        Demo source = (Demo) a.getSource();
        System.out.println("source = " + source.getId());
        System.out.println("source = " + source.getName());
        try {
            Thread.currentThread().sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程执行完成:"+Thread.currentThread().getName());
    }
}

 写一个controller用于调用测试

package com.example.jpademo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {
    @Autowired
    TopicEventPublisher publisher;

    private ApplicationEventPublisher applicationEventPublisher;

    @GetMapping("/push")
    public void send(String topic){
        Demo demo = new Demo();
        demo.setId("11111");
        demo.setName("张三");
        applicationEventPublisher.publishEvent(new Event_A(demo));
    }

}

 这个Demo类只是一个测试传输数据用的一个对象而已,换成其他类或者字符串等数据类型也不会有影响

如果需要这个测试demo的话,可以添加我qq找我要2102266433

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/866941.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号