zoukankan      html  css  js  c++  java
  • 在订单服务中使用Hystrix进行熔断设置

    使用Hystrix熔断(上)

    在一个分布式系统里,一个服务依赖多个服务,可能存在某个服务调用失败,

            比如超时、异常等,如何能够保证在一个依赖出问题的情况下,不会导致整体服务失败,

     

    使用实现降级

    1、复制项目并修改为新项目

        copy orderserver 为orderserverhystrix

            在项目右键修改名称orderserver为orderserverhystrix

            pom中修改artifactId为orderserverhystrix

            修改name为orderserverhystrix

            修改包名称luhq7.xdclass.orderserver为luhq7.xdclass.orderserverhystrix

            修改各种类名称增加hystrix

            在运行左侧的edit application中修改名称

    2、增加依赖到pom文件

         <dependency>

    <groupId>org.springframework.cloud</groupId>

    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>

    </dependency>

    3、启动类增加注解

            @EnableCircuitBreaker

            

            关注注解@SpringCloudApplication,包含以下注解

                @Target({ElementType.TYPE})

                @Retention(RetentionPolicy.RUNTIME)

                @Documented

                @Inherited

                @SpringBootApplication

                @EnableDiscoveryClient

                @EnableCircuitBreaker

    4、API接口编码实战

         熔断-》降级

     

            1)最外层api(controller包中)使用,好比异常处理(网络异常,参数或者内部调用问题)

                api方法上增加 @HystrixCommand(fallbackMethod = "saveOrderFail")

                    

                    save API中修改为

                     Map<String,Object> msg=new HashMap<>();

                                msg.put("code",0);

                                msg.put("msg",productOrderHystrixService.save(userId,productId));

                                return msg;

     

                编写fallback方法实现,方法签名一定要和api方法签名一致(注意点!!!)

     

                        private Object saveOrderFail(int userId,int productId)

                        {

                            Map<String,Object> msg=new HashMap<>();

                            msg.put("code",-1);

                            msg.put("msg","抢购人数太多!您被挤出来了,请稍等重试!");

                            return msg;

     

                        }

    5、为了体现熔断,将product-server停止后再访问下

    http://192.168.136.128:8769/api/v1/orderHystrix/save?userId=2&productId=2

     

    ok

  • 相关阅读:
    python的使用
    SFM(structure from motion)
    linux 常用命令
    opencv图像操作
    两圆位置判断
    nat123动态域名解析软件使用教程
    IIS负载均衡
    Oracle 查询表信息(字段+备注) .
    【原创】开源.NET排列组合组件KwCombinatorics使用(三)——笛卡尔积组合
    visual studio 2013使用技巧
  • 原文地址:https://www.cnblogs.com/programer-xinmu78/p/10520777.html
Copyright © 2011-2022 走看看