本文使用「署名 4.0 国际 (CC BY 4.0)」许可协议,欢迎转载、或重新修改使用,但需要注明来源。 署名 4.0 国际 (CC BY 4.0)
本文作者: Nicksxs
创建时间: 2022-01-30
本文链接: spring event 介绍
spring 框架中如果想使用一些一部操作,除了依赖第三方中间件的消息队列,还可以用 spring 自己的 event,简单介绍下使用方法首先我们可以建一个 event,继承 ApplicationEvent
public class CustomSpringEvent extends ApplicationEvent {
private String message;
public CustomSpringEvent(Object source, String message) { super(source); this.message = message; } public String getMessage() { return message; }}
复制代码
这个 ApplicationEvent 其实也比较简单,内部就一个 Object 类型的 source,可以自行扩展,我们在自定义的这个 Event 里加了个 Message ,只是简单介绍下使用
public abstract class ApplicationEvent extends EventObject { private static final long serialVersionUID = 7099057708183571937L; private final long timestamp;
public ApplicationEvent(Object source) { super(source); this.timestamp = System.currentTimeMillis(); }
public ApplicationEvent(Object source, Clock clock) { super(source); this.timestamp = clock.millis(); }
public final long getTimestamp() { return this.timestamp; }}
复制代码
然后就是事件生产者和监听消费者
@Componentpublic class CustomSpringEventPublisher {
@Resource private ApplicationEventPublisher applicationEventPublisher;
public void publishCustomEvent(final String message) { System.out.println("Publishing custom event. "); CustomSpringEvent customSpringEvent = new CustomSpringEvent(this, message); applicationEventPublisher.publishEvent(customSpringEvent); }}
复制代码
这里的 ApplicationEventPublisher 是 Spring 的方法接口
@FunctionalInterfacepublic interface ApplicationEventPublisher { default void publishEvent(ApplicationEvent event) { this.publishEvent((Object)event); }
void publishEvent(Object var1);}
复制代码
具体的是例如 org.springframework.context.support.AbstractApplicationContext#publishEvent(java.lang.Object, org.springframework.core.ResolvableType) 中的实现,后面可以展开讲讲
事件监听者:
@Componentpublic class CustomSpringEventListener implements ApplicationListener<CustomSpringEvent> { @Override public void onApplicationEvent(CustomSpringEvent event) { System.out.println("Received spring custom event - " + event.getMessage()); }}
复制代码
这里的也是 spring 的一个方法接口
@FunctionalInterfacepublic 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()); }; }}
复制代码
然后简单包个请求
@RequestMapping(value = "/event", method = RequestMethod.GET) @ResponseBody public void event() { customSpringEventPublisher.publishCustomEvent("hello sprint event"); }
复制代码
就能看到接收到消息了。
评论