springboot事件監聽

风吹南下發表於2024-08-25

一、定義事件

package com.base.common.event;

import com.base.common.core.domain.entity.SysUser;
import org.springframework.context.ApplicationEvent;

public class MyCustomEvent extends ApplicationEvent {

    private SysUser user;

    public MyCustomEvent(Object source, SysUser user) {
        super(source);
        this.user = user;
    }

    public SysUser getUser() {
        return user;
    }
}

二、定義事件監聽

自定義非同步方法寫法:

package com.base.common.event;

import com.base.common.core.domain.entity.SysUser;
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 MyCustomEventListener{

    @EventListener
    @Async
    public void MyCustomListener(MyCustomEvent event) throws Exception {
        SysUser user = event.getUser();
        Thread.sleep(3000);
        log.info("bean-listener 收到了 publisher 釋出的訊息: " + user.getUserName());
    }


}

實現ApplicationListener介面寫法:

package com.base.common.event;

import com.base.common.core.domain.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MyCustomEventListener implements ApplicationListener<MyCustomEvent> {
    @Override
    @Async
    public void onApplicationEvent(MyCustomEvent event) {
        SysUser user = event.getUser();
        try {
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("bean-listener 收到了 publisher 釋出的訊息: " + user.getUserName());
    }

}

三、釋出事件

@Slf4j
@RestController
@RequestMapping("/system/user")
@AllArgsConstructor
public class SysUserController extends BaseController {

    private final ISysUserService userService;
    private final ApplicationContext context;

    @PostMapping("/send")
    public AjaxResult send() {
        String message = "傳送成功";

        SysUser sysUser = userService.selectUserById(1L);

        MyCustomEvent event = new MyCustomEvent(this, sysUser);
        context.publishEvent(event);

        return success(message);
    }

}

相關文章