springcloud——hystrix服务提供者方服务降级

1、service

package com.springcloud.service;

import ch.qos.logback.core.util.TimeUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author dc
 * @date 2020/7/29 - 10:24
 */
@Service
public class PaymentService {

    /**
     * 正常访问,肯定OK
     * @param id
     * @return
     */
    public String paymentInfo_OK(Integer id) {
        return "线程池:" + Thread.currentThread().getName() + " paymentInfo_OK,id:" + id + "\t" + "O(∩_∩)哈哈~";
    }



    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties =
            {@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",
            value="3000")})
    //name:属性名      value:属性值
    //execution.isolation.thread.timeoutInMilliseconds:最大超时时间,如果业务方法执行时间超过该值,
    //就进入服务降级方法(fallbackMethod)
    public String paymentInfo_TimeOut(Integer id) {

        int timeNumber = 5;
        //计算异常同样可以用(同超时异常)
		//inta = 10/0;
        //线程睡眠3秒
        try {
            TimeUnit.SECONDS.sleep(timeNumber);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池:" + Thread.currentThread().getName() + " paymentInfo_TimeOut,id:" + id + "\t" + "O(∩_∩)哈哈~" + " 耗时" + timeNumber + "秒钟";
    }

    public String paymentInfo_TimeOutHandler(Integer id) {

        return "线程池: " + Thread.currentThread().getName() + "paymentInfo_TimeOutHandler, id: "
                + id + "\t" +"服务超时处理";

    }


}

2、主启动类

package com.springcloud;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

/**
 * @author dc
 * @date 2020/7/28 - 10:51
 */
@SpringBootApplication
@Slf4j
@EnableEurekaClient
@EnableCircuitBreaker   //服务降级使能注解
public class PaymentHystrixMain8081 {

    public static void main(String[] args) {
        SpringApplication.run(PaymentHystrixMain8081.class, args);
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_43925059/article/details/107691998