美文网首页基础知识
spring event 使用

spring event 使用

作者: Learn_Java | 来源:发表于2018-08-17 14:25 被阅读99次

使用场景

在开发中有些重要业务需要记录日志并保存.使用spring event 事件发布日志,统一监听日志并记录.使代码松耦合

使用

maven依赖

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

其实只要依赖spring-core就行了,但是我要用到mvc测试所以用了web依赖

定义日志发布类

public class LogEvent extends ApplicationEvent {

    private String log;

    public LogEvent(Object source, String log) {
        super(source);
        this.log = log;
    }

    public String getLog() {
        return log;
    }
}

定义日志监听类

@Slf4j
@Component
public class LogListener implements ApplicationListener<LogEvent> {

    public static Queue<String> queue = new LinkedList<>();

    @Override
    public void onApplicationEvent(LogEvent logEvent) {
        log.info("LogListener: {} ", logEvent.getLog());
        // you can save db
        queue.add(logEvent.getLog());
    }
}

发布

@SpringBootApplication
@RestController
public class SpringEventApplication {

    @Autowired
    private ApplicationContext applicationContext;

    public static void main(String[] args) {
        SpringApplication.run(SpringEventApplication.class, args);
    }

    @GetMapping("/")
    public String publishLogTest() {
        applicationContext.publishEvent(new LogEvent(this, "publish Log Test It's work!"));
        return LogListener.queue.poll();
    }
}

监听结果

  • 日志输出
2018-08-17 14:13:49.465  INFO 3596 --- [nio-8080-exec-6] com.example.spring.event.LogListener     : LogListener: publish Log Test It's work! 
2018-08-17 14:13:49.566  INFO 3596 --- [nio-8080-exec-7] com.example.spring.event.LogListener     : LogListener: publish Log Test It's work! 
  • 浏览器显示


    image.png

示例代码github地址

https://github.com/gbKidCoding/example-spring-event

问题

  • 通过log会看到事件被监听了2次,会在以后的文章中解决

END

相关文章

  • spring event 使用

    使用场景 在开发中有些重要业务需要记录日志并保存.使用spring event 事件发布日志,统一监听日志并记录....

  • Spring Event使用

    SpringEvent 自定义事件链,实用性很强的一种设计,可以利用它来做业务剥离,复杂场景解耦、代码独立等,也是...

  • spring-boot event

    spring-boot 事件模型: event - listenter event ApplicationEven...

  • Spring事件源码解析

    Spring事件监听源码分析 众所周知,在Spring中集成了内部的消息分发机制,可以在代码中使用注解@Event...

  • Spring Event & SpringBoot Event

    最近看到有说 Spring Event和SpringBoot Event两种 Event仔细看才知道,他们将Spr...

  • Spring Event

    Spring Event Observer Design Pattern Scenario Elvis, Jame...

  • spring event

    spring event的事件驱动模型的最佳实践@EventListenerhttps://blog.csdn.n...

  • Spring Event-Driven Architecture

    前言 Spring Event-Driven 是Java生态中关于Event-Driven编程范式的最佳实践标准之...

  • Spring中的事件讲解(Application Event)

    1 Spring事件简介 当Spring的事件(Application Event)为Bean和Bean之间的消息...

  • Spring Event的同步和异步,以及实现机制

    Spring Event 通知机制,可以很有效的帮助项目中的代码解耦合。咱们来看下它的同步和异步使用方式,以及相应...

网友评论

    本文标题:spring event 使用

    本文链接:https://www.haomeiwen.com/subject/uvlzbftx.html