其他分享
首页 > 其他分享> > 通过函数式参数对行为解耦

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

作者:互联网

描述:在我们平时的微服务开发中,调用其他服务的接口,通常要把接口调用部分做异常处理(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;
    }
}

 



标签:return,函数,vin,value,参数,catch,行为,public,String
来源: https://www.cnblogs.com/charkey/p/14767872.html