Spring Cloud Hystrix记录错误日志

Spring Cloud Hystrix捕捉异常信息

1.pom.xml

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>

2.在程序的启动类ServiceApplication 加@EnableHystrix注解开启Hystrix:

@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
public class ServiceApplication {

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

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

}

3.在hiService方法上加上@HystrixCommand注解

@Service
public class HelloService {

    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "hiError")
    public String hiService(String name) {
        return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class);
    }

	/**
     * 方法simpleHystrixClientCall的回退方法,可以指定将hystrix执行失败异常传入到方法中
     * @param name 必须跟hiService参数一致
     * @param e 执行失败的异常对象,非必须
     */
    public String hiError(String name, Throwable e) {
		System.out.println("错误信息:"+e.getMessage());
        return "hi,"+name+",sorry,error!";
    }
}

4.配置文件关键代码

#断路器,断路器跳闸后等待多长时间重试
hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds=1000
#断路器,请求发出后多长时间超时,默认一秒
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000

猜你喜欢

转载自blog.csdn.net/u011974797/article/details/80675994