JAVA 中使用 通知 进行解耦

起因

项目需求中有考试业务培训业务 两块,考试业务 准备做成通用模块,模块独立,仅对外暴露 考试实例 的ID,培训模块 若想知道 考试的具体内容,拿着 考试实例 ID去查看。
当用户提交考试结果的时候,考试模块进行各种算分操作,同时呢,培训业务 也需要需要进行算分以及修改 培训各种状态 的操作,所以在 考试结果 提交时,进行持久化的同时,要通知到 培训业务 进行培训的各种逻辑计算。

通知接口

/**
 * Summary : 通知接口
 *
 * @Author Ray
 * @Create 2020-08-13 9:50
 */
public interface Notifier<T> {
    /**
     * 通知
     *
     * @param t 通知内容
     */
    void notifier(T t);
}

考试结果 服务类

/**
 * Summary : 试卷实例的考试结果服务
 *
 * @Author Ray
 * @Create 2020-08-04 23:09
 */
@Service
public class OnlineExamInstanceResultService {
    /**
     * 关注者集合
     */
    public static ArrayList<Notifier<OnlineExamInstanceResult>> notifiers = new ArrayList<>();
    /**
     * 考试结果提交
     */
    @Transactional(rollbackFor = Exception.class)
    public OnlineExamInstanceResult c(@NotNull OnlineExamInstanceResult onlineExamInstanceResult) throws Exception {
        //讲 考试结果 通知 关注者们
        notifierAll(examInstanceResult);
        return examInstanceResult;
    }

    /**
     * 通知followers
     *
     * @param onlineExamInstanceResult 试卷实例的考试结果
     */
    private void notifierAll(OnlineExamInstanceResult onlineExamInstanceResult) {
        for (Notifier<OnlineExamInstanceResult> notifier : notifiers) {
            notifier.notifier(onlineExamInstanceResult);
        }
    }

培训业务 服务类

/**
 * Summary : 培训参与人
 *
 * @Author Ray
 * @Create 2020-08-11 18:09
 */
@Slf4j
@Service
public class OnlineTrainingParticipantService {

    @PostConstruct
    public void followExamInstanceResult() {
    	//将自己注册到 考试结果 的 通知集合中,当有考试结果出现的时候,会执行updateExamInstanceResultIfExist方法
        OnlineExamInstanceResultService.notifiers.add(this::updateExamInstanceResultIfExist);
    }

    /**
     * 将考试结果 异步写入 到的 对应的培训参与人
     *
     * @param onlineExamInstanceResult 考试结果
     */
    @Async
    void updateExamInstanceResultIfExist(@NotNull OnlineExamInstanceResult onlineExamInstanceResult) {
       
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值