在《spring cloud 微服务实战》第155页至156页,服务降级这一部分,定义服务降级的方式要根据你的请求命令实现方式,如果你是通过继承HystrixCommand来创建请求命令的,那么服务降级就可以通过重写getFallback()方法来实现:
public class UserCommand extends HystrixCommand<User>{ private RestTemplate restTemplate; private Long id; public UserCommand(Setter setter,RestTemplate restTemplate,Long id){ super(setter); this.restTemplate=restTemplate; this.id=id; } @Override protected User run() throws Exception { return restTemplate.getForObject("http://localhost:8081/users/{1}",User.class,id); } @Override protected User getFallback() {//重写服务降级方法 return new User(3,"test"); } }
如果通过注解@HystrixCommand的方式来实现的话,服务降级就要在注解中添加fallbackMethod参数来指定具体的服务降级实现方法:
@Service public class UserService { @Autowired RestTemplate restTemplate; @HystrixCommand(fallbackMethod = "defaultUser") public User getUserById(Long id){ Integer.parseInt("wd"); return restTemplate.getForObject("http://USER-SERVICE/users/{1}",User.class,id); } public User defaultUser(Long id){//书上这里少了参数 return new User(4,"gg"); }我没用过旧版本的springcloud(例如Angel、Brixton),不知道是不是旧版本在指定服务降级方法时就可以不带参数呢?(我没验证过),还是作者忘了?反正你如果用的是Dalston版本,这里的defaultUser方法如果和getUserById方法参数不一致的话会报错:com.netflix.hystrix.contrib.javanica.exception.FallbackDefinitionException:
fallback method wasn't found: defaultUser([class java.lang.Long])