服务容错保护(Spring Cloud Hystrix)之服务降级

服务降级是在Hystrix命令执行失败时的一种备用方案,在HystrixCommand中可以通过重载getFallback()方法来实现服务降级逻辑处理,Hystrix会在run()执行霍城中出现错误,超时,线程池拒绝,断路器熔断等情况时,执行降级逻辑。

继承方式:

package com.ribbon;

import com.netflix.hystrix.HystrixCommand;
import org.springframework.web.client.RestTemplate;

/**
 * Created by qhe on 2018/7/26.
 *
 * 创建请求命令
 * 继承的方式实现封装具体的依赖服务调用逻辑
 *
 */
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://user-service/hello/user/{1}",User.class,id);
    }

    /**
     * 服务降级
     * @return
     */
    @Override
    protected User getFallback(){
        return new User();
    }
}

注解方式:

package com.ribbon;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.command.AsyncResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.Future;

/**
 * Created by wangjing on 2018/7/26.
 *
 *
 * 创建请求命令
 * 利用注解形式
 */
public class UserService {

    @Autowired
    private RestTemplate restTemplate;

    /**
     *同步
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "defaultUser")
    public User getUserById(Long id){
        return restTemplate.getForObject("http",User.class,id);
    }

    /**
     * 虽然是getUserById的降级逻辑,但是还是可以继续用注解指定再降级
     * @return
     */
    @HystrixCommand(fallbackMethod = "dedalutUserSec")
    public User defaultUser(){
        //此处可能是另外一个网络请求来获取,所以也有可能失败
//        return new User();
        //捕获异常
        throw new RuntimeException("failed");
    }

    public  User dedalutUserSec(String id,Throwable e){
//       return new User();
        //根据不同异常进行降级处理
        assert "failed".equals(e.getMessage());
        return null;
    }
}

猜你喜欢

转载自blog.csdn.net/hq091117/article/details/81236796