【spring 事件驱动】spring 事件驱动

Spring事件驱动,在spring boot中使用spring 的事件模型。事件模型包含 事件类,事件监听器,注册事件监听器,事件发布者。以下代码功能:1.自定义监听器执行顺序 2.监听器由线程池异步执行。1和2是互斥关系,稍稍改动即可

package com.example.demo.springevent;

import org.springframework.context.ApplicationEvent;

public class StudentEvent extends ApplicationEvent {

    String id;
    String name;
    Integer price;

    public StudentEvent(Object source,String id,String name, Integer price) {
        super(source);
        this.id=id;
        this.name =name;
        this.price =price;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Integer getPrice() {
        return price;
    }
}





package com.example.demo.springevent.e3.e2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.concurrent.Executor;

/**
 *   监听器
 */
@Configuration
@EnableAsync
public class AppliOederConfig {


    /**
     * 因此,当Spring容器启动时,它会调用taskExecutor()方法创建一个ThreadPoolTaskExecutor对象,并将其注册为一个bean。
     *
     * 这样,你就可以在其他组件中使用@Autowired注解来注入Executor对象,并在应用程序中共享同一个线程池实例。
     * @return
     */
    @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(100);
        executor.setQueueCapacity(10);
        executor.setThreadNamePrefix("Async-");
        executor.initialize();
        return executor;
    }
    @Bean
    public StudentEventListenerInBookOrder studentEventListenerInBookOrder(Executor executor)  {
        return new StudentEventListenerInBookOrder(executor);
    }

    @Bean
    public StudentEventListenerInFoodOrder studentEventListenerInFoodOrder(Executor executor)  {
        return new StudentEventListenerInFoodOrder(executor);
    }

    @Bean
    public StudentEventListenerInWifiOrder studentEventListenerInWifiOrder(Executor executor) {
        return new StudentEventListenerInWifiOrder(executor);
    }

    @Bean
    public StudentEventListenerInWaterOrder studentEventListenerInWaterOrder(Executor executor)  {
        return new StudentEventListenerInWaterOrder(executor);
    }


}
package com.example.demo.springevent.e3.e2;

import com.example.demo.springevent.StudentEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.scheduling.annotation.Async;

import java.util.concurrent.Executor;

/**
 * 处理学生的图书信息记录,监听器,可自定义监听器执行的顺序
 */
@Slf4j
public class StudentEventListenerInBookOrder implements SmartApplicationListener {
    private final Executor executor;

    public StudentEventListenerInBookOrder(Executor executor) {
        this.executor = executor;
    }


    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return eventType == StudentEvent.class;
    }

    @Async//使用异步线程执行监听器   1.启动类  @EnableAsync  2.注册类  @EnableAsync  3.监听器方法
    @Override
    public void onApplicationEvent(ApplicationEvent event) {

        executor.execute(() -> {
            StudentEvent studentEvent = (StudentEvent) event;
            String id = studentEvent.getId();
            String name = studentEvent.getName();
            int price = studentEvent.getPrice();
            log.info("y1图书信息清零,处理完毕" + id + "  " + name + "   " + price + " " + Thread.currentThread().getId() + " " + Thread.currentThread().getName());

        });
    }

/**
SmartApplicationListener中的getOrder()方法只能在同一个线程中起作用,
用于定义监听器的执行顺序。
但是,当任务提交到线程池中执行时,不同的任务可能会被分配给不同的线程,因此无法保证它们的执行顺序。

*/
/**
如果需要保证自定义的执行顺序,一种可行的方法是使用单线程的Executor,例如SingleThreadExecutor。这样,任务将按照提交的顺序一个接一个地执行,保证了自定义的执行顺序。
或者不使用线程池
*/
    @Override
    public int getOrder() {//对监听器执行事件的顺序排序,使用SmartApplicationListener
        return 1;//数字越小,优先级越高
    }
}

package com.example.demo.springevent.e3.e2;

import com.example.demo.springevent.StudentEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;

/**
 * 处理学生的 食堂饭卡 信息,监听器,可自定义监听器执行的顺序
 */
@Slf4j
public class StudentEventListenerInFoodOrder implements SmartApplicationListener {

    private final Executor executor;

    public StudentEventListenerInFoodOrder(Executor executor) {
        this.executor = executor;
    }


    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return eventType == StudentEvent.class;
    }

    @Async
    @Override
    public void onApplicationEvent(ApplicationEvent event) {

        executor.execute(() -> {
            StudentEvent studentEvent = (StudentEvent) event;
            String id = studentEvent.getId();
            String name = studentEvent.getName();
            int price = studentEvent.getPrice();
            log.info("y2饭卡信息清零,处理完毕" + id + "  " + name + "   " + price + " " + Thread.currentThread().getId() + " " + Thread.currentThread().getName());

        });
    }

    @Override
    public int getOrder() {
        return 2;
    }
}

package com.example.demo.springevent.e3.e2;

import com.example.demo.springevent.StudentEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * 处理学生的 网络信息 ,监听器,可自定义监听器执行的顺序
 */
@Slf4j
public class StudentEventListenerInWaterOrder implements SmartApplicationListener {

    private final Executor executor;

    public StudentEventListenerInWaterOrder(Executor executor) {
        this.executor = executor;
    }

    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return eventType == StudentEvent.class;
    }

    @Async
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        executor.execute(() -> {
            StudentEvent studentEvent = (StudentEvent) event;
            String id = studentEvent.getId();
            String name = studentEvent.getName();
            int price = studentEvent.getPrice();
            log.info("y3网络信息清零,处理完毕" + id + "  " + name + "   " + price + " " + Thread.currentThread().getId() + " " + Thread.currentThread().getName());

        });
    }
    @Override
    public int getOrder() {
        return 3;
    }
}

package com.example.demo.springevent.e3.e2;

import com.alibaba.fastjson.JSON;
import com.example.demo.springevent.StudentEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Service;

@Service("publisher2")
@Slf4j
public class StudentEventPublisher2 {

    public void publishStudentEvent() {
        // 创建 Spring 应用程序上下文
        ApplicationContext context = new AnnotationConfigApplicationContext(AppliOederConfig.class);

        // 获取事件发布器
        ApplicationEventPublisher publisher = context;

        // 创建自定义事件对象
        StudentEvent studentEvent = new StudentEvent(new Object(), "y", "yyyy", 8888);

        log.info("发布事件,{}", JSON.toJSONString(studentEvent));
        // 发布事件
        publisher.publishEvent(studentEvent);

    }
}

package com.example.demo.service;

import com.example.demo.springevent.e2.StudentEventPublisher1;
import com.example.demo.springevent.e3.e2.StudentEventPublisher2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class BuildData implements ApplicationRunner {

    @Resource(name = "publisher2")
    StudentEventPublisher2 studentEventPublisher2;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("ApplicationRunner方法执行");
        // 启动线程
       studentEventPublisher2.publishStudentEvent();
    }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值