场景说明:在使用SpringBoot时,总是要添加一大堆自定义事件,实现ApplicationEvent,来实现事件发送。
这样写代码量非常大。为了方便和避免出错,封装自定义的模块,快速实现泛型中调用SpringEvent实现事件。省去配置,简化代码,增加多线程并发处理。
一、配置自定义注解和泛型事件
1、添加自定义注解来开启配置
import org.springframework.context.annotation.Import;import java.lang.annotation.*;/*** 自动启用 Spring Event事件*/ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Import({QySpringEventConfiguration.class}) @Documented public @interface EnableQySpringEvent { }
2、自定义配置中,设置线程池和注入配置
import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.event.SimpleApplicationEventMulticaster; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;/*** 配置,加载EventBus事件总线*/ @Configuration @EnableAsync // 自动开启异步处理 @Slf4j public class QySpringEventConfiguration {private final ApplicationContext applicationContext;@Autowiredpublic QySpringEventConfiguration(ApplicationContext applicationContext) {this.applicationContext = applicationContext;}@Beanpublic QyEventService qySpringEventService() {log.info("<<<<<<<<<<<<<<< 注入QyEventService实现自定义事件 >>>>>>>>>>>>>>>>>>");return new QySpringEventServiceImpl(applicationContext);}/*** 指定线程池,专用于事件订阅和发布** @return*/@Bean(name = "eventTaskExecutor")public TaskExecutor eventTaskExecutor() {ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();taskExecutor.setThreadNamePrefix("qy-springEventTaskExecutor-");taskExecutor.setCorePoolSize(5);taskExecutor.setQueueCapacity(100);taskExecutor.setMaxPoolSize(5);taskExecutor.initialize();return taskExecutor;}/*** 为SpringEvent指定线程池* 注意beanName必须为applicationEventMulticaster;下面的源码中你将看到** @param beanFactory* @return*/@Bean(name = AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME)public SimpleApplicationEventMulticaster eventMulticaster(BeanFactory beanFactory) {SimpleApplicationEventMulticaster eventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);eventMulticaster.setTaskExecutor(eventTaskExecutor());return eventMulticaster;}}
3、定义支持泛型的事件,省去每次配置ApplicationEvent的过程
import lombok.Getter; import lombok.Setter; import org.springframework.context.ApplicationEvent; import org.springframework.core.ResolvableType; import org.springframework.core.ResolvableTypeProvider;/*** 带泛型的多重使用器** @param <T>*/ @Setter @Getter public class QyEvent<T> extends ApplicationEvent implements ResolvableTypeProvider {private T data;public QyEvent(T data) {super(data);this.data = data;}public QyEvent(Object source, T data) {super(source);this.data = data;}@Overridepublic ResolvableType getResolvableType() {return ResolvableType.forClassWithGenerics(getClass(), ResolvableType.forInstance(data));} }
4、定义发送服务
/*** Spring内部自带的事件发布器*/ public interface QyEventService {/*** 发布事件** @param qyEvent*/<T> void publishEvent(QyEvent<T> qyEvent);}
5、服务实现类
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component;@Component public class QySpringEventServiceImpl implements QyEventService {private final ApplicationContext applicationContext;@Autowiredpublic QySpringEventServiceImpl(ApplicationContext applicationContext) {this.applicationContext = applicationContext;}@Overridepublic <T> void publishEvent(QyEvent<T> qyEvent) {applicationContext.publishEvent(qyEvent);} }
更多精彩内容关注我的公众号:青塬科技。
二、在使用时
1、在入口处添加注解
@EnableQySpringEvent
2、使用时,在服务中添加
@Resource
QyEventService qyEventService;
测试发送消息内容:
IntStream.rangeClosed(0, 10).forEach(item -> {qyEventService.publishEvent(new QyEvent<>("test" + item)); });
3、添加监听器
import lombok.extern.slf4j.Slf4j; import org.springframework.context.event.EventListener; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component;/*** 事件监听处理器*/ @Component @Slf4j public class QyEventListener {@Async // 异步实现@EventListener // 监听器,会自动识别类型public void onOperationLogEvent(QyEvent<String> event) {log.info("QyEvent Listener recieve message: " + event.getData());} }
日志显示:
2024-05-21 14:51:22.798 INFO 14757 --- [qy-springEventTaskExecutor-1] c.q.justtest.listener.QyEventListener : QyEvent Listener recieve message: test5 2024-05-21 14:51:22.798 INFO 14757 --- [qy-springEventTaskExecutor-3] c.q.justtest.listener.QyEventListener : QyEvent Listener recieve message: test3 2024-05-21 14:51:22.798 INFO 14757 --- [qy-springEventTaskExecutor-2] c.q.justtest.listener.QyEventListener : QyEvent Listener recieve message: test4 2024-05-21 14:51:22.798 INFO 14757 --- [qy-springEventTaskExecutor-4] c.q.justtest.listener.QyEventListener : QyEvent Listener recieve message: test6 2024-05-21 14:51:22.798 INFO 14757 --- [qy-springEventTaskExecutor-1] c.q.justtest.listener.QyEventListener : QyEvent Listener recieve message: test7 2024-05-21 14:51:22.798 INFO 14757 --- [qy-springEventTaskExecutor-4] c.q.justtest.listener.QyEventListener : QyEvent Listener recieve message: test1 2024-05-21 14:51:22.798 INFO 14757 --- [qy-springEventTaskExecutor-4] c.q.justtest.listener.QyEventListener : QyEvent Listener recieve message: test8 2024-05-21 14:51:22.798 INFO 14757 --- [qy-springEventTaskExecutor-1] c.q.justtest.listener.QyEventListener : QyEvent Listener recieve message: test9 2024-05-21 14:51:22.798 INFO 14757 --- [qy-springEventTaskExecutor-4] c.q.justtest.listener.QyEventListener : QyEvent Listener recieve message: test2 2024-05-21 14:51:22.798 INFO 14757 --- [qy-springEventTaskExecutor-2] c.q.justtest.listener.QyEventListener : QyEvent Listener recieve message: test0 2024-05-21 14:51:22.798 INFO 14757 --- [qy-springEventTaskExecutor-3] c.q.justtest.listener.QyEventListener : QyEvent Listener recieve message: test10
可以发现已经实现多线程,并且并发打印出消息。
总结
关于多线程的内容已经说完了,但是我还想说点别的,主要想说一下我们应该学习哪些技术才能让它更加保值。
在我看来,越偏向于业务的技术越不容易过时,为什么呢?需求在变,技术一直在变,业务也一直在迭代。前端技术的发展非常快,也涌现出很多的框架(例如 HTML4 到 HTML5 的升级,或者从jQuery 到前端三大框架的转变),但是总归就是两个字:效率。
作为开发者,我们需要保持好奇心和学习热情,不断探索新的技术,只有这样,我们才能在这个快速发展的时代中立于不败之地。介绍一款程序员都应该知道的软件JNPF快速开发平台,很多人都尝试用过它,它是功能的集大成者,任何信息化系统都可以基于它开发出来。
JNPF可以实现应用从创建、配置、开发、测试到发布、运维、升级等完整生命周期的管理。减少了传统应用程序的代码编写量,通过图形化、可视化的界面,以拖放组件的方式,即可快速生成应用程序的产品,大幅降低了开发企业管理类软件的难度。
当然,我更建议大家成为一个全栈,不要把自己的定位局限于前端。