zoukankan      html  css  js  c++  java
  • java 微服务通过 设置超时时间或者捕捉异常 的方式处理 微服务挂掉或者其他异常问题

      废话不多说直接上代码

      服务端:

      我们可以看出来服务端的方法里面 10/0 是必报错的

      

        @Resource
        private PaymentService paymentService;
    
    @GetMapping("/payment/hystrix/paymentInfo_Error")
        public CommonResult paymentInfo_Error() {
            String result= paymentService.paymentInfo_Error();
            log.info("*******result:"+result);
            if(result.equals("服务异常"))
            {
                return  new CommonResult(301,"服务异常",null);
            }
            return  new CommonResult(200,"服务成功",null);
        }
    package com.aty.springcloud.service;
    
    import cn.hutool.core.util.IdUtil;
    import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
    import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
    import org.springframework.stereotype.Service;
    import org.springframework.web.bind.annotation.PathVariable;
    
    import java.util.concurrent.TimeUnit;
    
    /**
     * Created by vcyber
     */
    @Service
    public class PaymentService {
         
        /**
        * @Description: 模拟服务异常
        * @Param:  * @param null
        * @return:
        * @Author: 杨金旺
        * @Date: 2020/7/9
        */
        public  String paymentInfo_Error()
        {
           try{
                int timeNumder=10/0;
             
            }catch (Exception e)
            {
                 e.printStackTrace();
                 return  "服务异常";
            }
            return  "服务成功";
        }
    }

      消费端代码:

      PAYMENT_URL 是服务端的服务名

     // 通过捕捉 异常 解决 微服务异常
        @GetMapping("/consumer/payment/paymentInfo_Error")
        public  CommonResult paymentInfo_Error()
        {
            try {
                ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/hystrix/paymentInfo_Error", null, CommonResult.class);
    
                if (entity.getStatusCode().is2xxSuccessful()) {
                    log.info("响应状态码:" + entity.getStatusCode() + ",headers:" + entity.getHeaders());
                    return new CommonResult<>(200, "操作结果:" + entity.getBody()); //entity.getBody();
                } else {
                    return new CommonResult<>(444, "操作失败");
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
                return new CommonResult<>(555, "调用服务出现异常");
            }
        }
    
        private static ExecutorService executorService = Executors.newSingleThreadExecutor();
        // 通过设置超时 解决 微服务异常
        @GetMapping("/consumer/payment/timeout")
        public  CommonResult timeout()
        {
            try {
                /*
                ExecutorService executor = Executors.newSingleThreadExecutor();
                FutureTask<CommonResult> future = new FutureTask<CommonResult>(new Callable<List<Object[]>>()*/
    
                FutureTask<ResponseEntity<CommonResult>> futureTask = new FutureTask<>(new Callable<ResponseEntity<CommonResult>>() {
    
                    @Override
                    public ResponseEntity<CommonResult> call() throws Exception {
                        ResponseEntity<CommonResult> c=  restTemplate.getForEntity(PAYMENT_URL + "/payment/hystrix/paymentInfo_Error", null, CommonResult.class);
                        return c;
                    }
                });
                executorService.execute(futureTask);
                try {
                    ResponseEntity<CommonResult>  result = futureTask.get(1, TimeUnit.MILLISECONDS);
                    return new CommonResult<>(200, "操作结果:" + result.getBody()); //entity.getBody();
                } catch (InterruptedException | ExecutionException | TimeoutException e) {
                    //e.printStackTrace();
                    futureTask.cancel(true);
                    return new CommonResult<>(666, "调用服务超时");
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
                return new CommonResult<>(555, "调用服务出现异常");
            }
        }

      Template 类

      

    @Configuration
    public class ApplicationContextConfig {
        @Bean
        @LoadBalanced   // 默认轮询
        public RestTemplate getRestTemplate()
        {
            return new RestTemplate();
    
        }
    }

    服务端启用 捕捉异常的 调用结果:

    服务端未启用 通过超时设置的 调用结果:

     

  • 相关阅读:
    hadoop学习笔记(十):MapReduce工作原理(重点)
    hadoop学习笔记(九):MapReduce程序的编写
    hadoop学习笔记(八):MapReduce
    hadoop学习笔记(七):Java HDFS API
    hadoop学习笔记(六):HDFS文件的读写流程
    hadoop学习笔记(五):HDFS Shell命令
    hadoop学习笔记(四):HDFS
    hadoop学习笔记(三):hadoop文件结构
    立即执行函数
    let命令
  • 原文地址:https://www.cnblogs.com/yangjinwang/p/13274490.html
Copyright © 2011-2022 走看看