Dubbo系列十:整合Hystrix

 Hystrix 旨在通过控制那些访问远程系统、服务和第三方库的节点,从而对延迟和故障提供更强大的容错能力。Hystrix具备拥有回退机制和断路器功能的线程和信号隔离,请求缓存和请求打包,以及监控和配置等功能。
1、引入spring-cloud-starter-netflix-hystrix依赖

    <!-- hystrix服务熔断-->
    <!-- 注意要选择与springboot对应的版本,否则会报错 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        <version>2.0.3.RELEASE</version>
    </dependency>

2、在主程序类上增加注解@EnableHystrix来开启hystrix功能

	@EnableHystrix //开启服务熔断
	@SpringBootApplication
	public class SpringbootServiceProviderApplication {
	
	    public static void main(String[] args) {
	        SpringApplication.run(SpringbootServiceProviderApplication.class, args);
	    }
	
	}

3、在服务提供者Provider上增加@HystrixCommand注解,这样调用就会经过Hystrix代理。

	@Service //暴露服务
	@Component
	public class UserServiceImpl implements UserService {
	
		@HystrixCommand  //表示方法被hystrix代理,出现异常就可以熔断了
		@Override
		public List<UserAddress> getUserAddressList(String userId) {
			UserAddress address1 = new UserAddress(1, "北京市昌平区宏福科技园综合楼3层", "1", "李老师", "010-56253825", "Y");
			UserAddress address2 = new UserAddress(2, "深圳市宝安区西部硅谷大厦B座3层(深圳分校)", "1", "王老师", "010-56253825", "N");
	
			if(Math.random()>0.5){
				throw new RuntimeException();
			}
			return Arrays.asList(address1,address2);
		}
	}

4、在服务消费者增加@HystrixCommand注解并指定出错时的回调方法。当调用出错时,会调用fallbackMethod = "hello"里面的指定的hello方法。

	@Service
	public class OrderServiceImpl implements OrderService {
	    
	    @Reference
	    UserService userService;
	
	    /**当方法报错时,由回调方法hello处理*/
	    @HystrixCommand(fallbackMethod = "hello")
	    @Override
	    public List<UserAddress> initOrder(String userId) {
	        System.out.println("用户id:"+userId);
	        //1、查询用户的收货地址
	        List<UserAddress> userAddressList = userService.getUserAddressList(userId);
	        return userAddressList;
	    }
	
	    /**服务熔断的回调方法*/
	    public List<UserAddress> hello(String userId) {
	        return Arrays.asList(new UserAddress(10,"服务熔断测试","1","服务熔断测试","服务熔断测试","Y"));
	    }
	}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值