在订单服务中使用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

posted @ 2019-03-13 08:27  心目  阅读(599)  评论(0编辑  收藏  举报