..

spring#事件发布订阅

1. 如果在应用中发生了某些事件,事件会被拦截和处理就好了,这样就有了很大的灵活性,至少代码不会紧密的耦合在一起,

代码的解耦就是业务的解耦,业务A的代码不用手动的调用业务B的代码,业务B只需要监听相关事件,根据事件处理业务就可以了。

 

 

2. 几个类:

  • 事件类:ApplicationEvent 继承 java.util.EventObject, 我们需要继承ApplicationEvent,必要时候为事件添加一些属性;
  • 事件发布类:ApplicationContext 继承了org.springframework.context.ApplicationEventPublisher,我们需要通过ApplicationContext.publisEvent(event)发布事件;
  • 事件处理类:ApplicationListener 继承了java.util.EventListener,我们需要实现ApplicationListener接口,并覆写处理事件的方法,完成事件处理逻辑。

 

3. 一个demo:

自定义事件:

import org.springframework.context.ApplicationEvent;

public class PermissionNeedReloadEvent extends ApplicationEvent {

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

}
View Code

自定义事件处理器:

import com.haonan.event.events.PermissionNeedReloadEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component // 通过注解把当前的事件处理器注入到spring容器中去
public class PermissionNeedReloadEventHandler implements ApplicationListener<PermissionNeedReloadEvent> {
    @Override
    public void onApplicationEvent(PermissionNeedReloadEvent permissionNeedReloadEvent) {
        System.out.println(Thread.currentThread().getName() + "------------------出事啦 @" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        // 这里我读取数据库中的权限信息,加载到内存中去,或者干一些其他相关的事情
    }
}
View Code

事件发布代码:

import com.haonan.event.events.PermissionNeedReloadEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    private ApplicationContext app;

    @GetMapping("/hello")
    public String addRole() {
        // 这里系统中添加一些角色信息
        // 逻辑代码

        // 当系统添加了角色信息,需要产生一个权限需要被重新加载的事件
        app.publishEvent(new PermissionNeedReloadEvent(this));
        return "success";
    }
}
View Code

 

posted @ 2019-11-13 21:43  罗浩楠  阅读(937)  评论(0)    收藏  举报
..