首页 > 其他 > 详细

通过函数式参数对行为解耦

时间:2021-05-14 15:48:54      阅读:8      评论:0      收藏:0      [点我收藏+]

描述:在我们平时的微服务开发中,调用其他服务的接口,通常要把接口调用部分做异常处理(try catch),或者打印异常日志或者结果日志,并且也有可能做一些统一的调用处理,比如微服务接口熔断等处理,这个时候可以适用函数式接口收拢所有的微服务调用集中处理

 

TestController2
    @RequestMapping(value = "/listByVin", method = RequestMethod.GET)
    public String listByType(@RequestParam(value = "vin") String vin) {
        //正常写法
        try {
            return testService2.handler1(vin);
        }catch (Exception e){
            e.printStackTrace();
        }

        //函数式写法
        return ServerExeutor.executeAndReturn(() -> testService2.handler1(vin));
    }


    @RequestMapping(value = "/listByVin2", method = RequestMethod.GET)
    public String listByVin2(@RequestParam(value = "vin") String vin,@RequestParam(value = "status") Short status) {
        //正常写法
        try {
            testService2.handler2(vin,status);
        }catch (Exception e){
            e.printStackTrace();
        }
        //函数式写法
        ServerExeutor.execute(() -> testService2.handler2(vin,status));
        return "执行不带参函数完成";
    }
ServerExeutor
public class ServerExeutor {
    public static void execute(Runnable runnable){
        try {
            runnable.run();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static String executeAndReturn(Callable<String> callable){
        try {
            return callable.call();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}

 



通过函数式参数对行为解耦

原文:https://www.cnblogs.com/charkey/p/14767872.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!