1.注解需要加载直接调用的方法上,嵌套方法调用不起作用,例如getUserSleepRibbonNotHystrixError
2.如果必须调用可以获取bean调用通过aop代理调用
3.如果不是spring管理的类,无法通过Aware获取ApplicationContext,可以考虑把ApplicationContext做成类变量
4.demo
package com.zhenzhen.demo.springcloud2.orderservice.service.impl;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zhenzhen.demo.springcloud2.orderservice.service.OrderService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class OrderServiceImpl implements OrderService, ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Autowired
private RestTemplate restTemplate;
public String getUserSleepRibbonNotHystrixError(String time) {
return getUserSleepRibbon(time);
}
public String getUserSleepRibbonNotHystrixOk(String time) {
return applicationContext.getBean(OrderServiceImpl.class).getUserSleepRibbon(time);
}
@Override
@HystrixCommand(fallbackMethod = "defaultStores")
public String getUserSleepRibbon(String time) {
return restTemplate.getForObject("http://USER/sleep?time="+time, String.class);
}
public String defaultStores(String time) {
return "服务发生降级";
}
}