springboot中使用责任链模式

责任链模式就是把所有的接口都构成一个链条,通过处理器程序来调用所有的链条,防止接口耦合

我们来实现注册的功能,一个注册调用链用于注册,一个短信调用链用于发送短信

两个调用链互相不干扰,注册成功后,2个接口都会执行

定义注册接口

public interface ZhuCeService {

    public boolean zhuce(String user);
}

创建注册链条 先执行,实现注册接口

package com.example.demo.service.impl;

import com.example.demo.service.ZhuCeService;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

/**
 *
 * 注册调用链
 * @param
 * @return
 * @throws Exception
 */
@Order(1)
@Service
public class ZhuCeChain implements ZhuCeService {
    @Override
    public boolean zhuce(String user) {
        if(user==null){
            return false;
        }
        System.out.println("注册成功");
        return true;
    }
}

创建短信链条,后执行,实现注册接口

package com.example.demo.service.impl;


import com.example.demo.service.ZhuCeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.List;
//根据order来指定谁先执行
@Order(2)
@Service
public class DuanXinChain implements ZhuCeService {



    @Override
    public boolean zhuce(String user) {
        if(user==null){
            return false;
        }
        System.out.println("发送短信成功");
        return true;
    }
}

创建注册的处理程序,调用所有的链条

package com.example.demo.config;

import com.example.demo.service.ZhuCeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 *
 * 注册处理器
 * @param
 * @return
 * @throws Exception
 */
@Component
public class ZhuCeHandler {

    @Autowired
    private List<ZhuCeService> zhuCeServices;

    /**
     *
     * 处理链条上所有的接口调用
     * @param
     * @return
     * @throws Exception
     */
    public void handler(String user){
        for (ZhuCeService x : zhuCeServices) {
           boolean flag= x.zhuce(user);
           if(!flag){
               //如果链条上有一个接口 失败了 那么直接停止
               break;
           }
        }
    }

}

控制层 调用注册处理程序

package com.example.demo.controller;

import com.example.demo.config.ZhuCeHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ZhuCeController {

    @Autowired
    private ZhuCeHandler zhuCeHandler;

    @GetMapping("/zhuce")
    public String zhuce(){
        //调用注册处理器
        zhuCeHandler.handler("123");
        return "注册成功";
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值