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();

    }
}

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

 

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

 

 

posted @ 2020-07-09 16:36  秋香姑娘请你不要紧张  阅读(1433)  评论(0编辑  收藏  举报