• spring cloud(断路器——初学五)


    Feign使用Hystrix

      因为feign已经依赖了hystrix,所以可以直接使用,无需添加再次添加依赖。

      1、使用@FeignClient注解中的fallback属性指定回调类

    package com.daqsoft;
    
    import org.springframework.cloud.netflix.feign.FeignClient;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    
    /**
     * @Description Created by liaoxx on 2017-6-12.
     */
    @FeignClient(value = "compute-service", fallback = ComputeClientHystrix.class)
    public interface ComputerClient {
        @RequestMapping(method = RequestMethod.GET, value = "/add")
        Integer add(@RequestParam(value = "a") Integer a, @RequestParam(value = "b") Integer b);
    }

      2、创建回调类ComputeClientHystrix,实现@FeignClient的接口,此时实现的方法就是对应@FeignClient接口中映射的fallback函数

    package com.daqsoft;
    
    import org.springframework.stereotype.Component;
    import org.springframework.web.bind.annotation.RequestParam;
    
    /**
     * @Description Created by liaoxx on 2017-6-13.
     */
    @Component
    public class ComputeClientHystrix implements ComputerClient {
        @Override
        public Integer add(@RequestParam(value = "a") Integer a, @RequestParam(value = "b") Integer b) {
            return -1;
        }
    }

      3、web调用

    package com.daqsoft;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * @Description Created by liaoxx on 2017-6-12.
     */
    @RestController
    public class CustomController {
    
        @Autowired
        private ComputerClient computerClient;
    
        @RequestMapping(value = "/add", method = RequestMethod.GET)
        public Integer add(){
            return computerClient.add(10,20);
    
        }
    }

      4、启动服务,访问http://localhost:3333/add

      

      报错,无法进入回调

      5、修改配置文件,添加属性

    spring.application.name=ribbon-consumer
    
    server.port=3333
    #服务注册中心地址
    eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/

    #开启hystrix支持 feign.hystrix.enabled=true

      6、再次启动服务,访问http://localhost:3333/add (正常访问回调方法)

      

      

  • 相关阅读:
    vscode 整理————开篇之力(一)
    重学c#系列——datetime 和 datetimeoffset[二十一]
    重新点亮shell————什么是shell[一]
    重新整理 .net core 实践篇——— 权限中间件源码阅读[四十六]
    为什么构建容器需要Namespace?
    基于Windows Mobile 5.0的掌上天气预报设计
    使用.NE平台调用服务访问非托管 DLL 中的函数
    .NET Framework 3.0 RC1 开发环境构建
    ASP.NET未处理异常的处理
    基于Silverlight的Windows Phone 推箱子程序开发
  • 原文地址:https://www.cnblogs.com/liao-xx/p/6999899.html
Copyright © 2020-2023  润新知