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

    }
}

服務端啟用 捕捉異常的 調用結果:

 

服務端未啟用 通過超時設置的 調用結果:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM