SpringMVC整合Hystrix

1、添加maven依赖

<dependency>
    <groupId>com.netflix.hystrix</groupId>
    <artifactId>hystrix-core</artifactId>
    <version>1.5.18</version>
</dependency>
<dependency>
    <groupId>com.netflix.hystrix</groupId>
    <artifactId>hystrix-javanica</artifactId>
    <version>1.5.18</version>
</dependency>

2、配置切面

<aop:aspectj-autoproxy proxy-target-class="true" />
<bean class="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect" />

3、编写controller类,并添加注解

@Controller
@RequestMapping
public class CommonController {
    /**
     * 主页
     * 
     * @return
     */
    @RequestMapping("/")
    public String home() {
        return "home.html";
    }

    /**
     * 配置2秒超时,超时后调用testFallback方法返回到error界面<br>
     * 当并发量比较大时,并非所有阻断或失败的请求都会走fallback方法,当处理线程忙不过来时,会直接抛出HystrixRuntimeException异常
     * 
     * @param mav
     * @param time 睡眠时间
     * @return
     */
    @HystrixCommand(groupKey = "groupTest", commandKey = "commandTest", fallbackMethod = "testFallback", commandProperties = {
            @HystrixProperty(name = "execution.timeout.enabled", value = "true"),
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000") })
    @RequestMapping("/test")
    public ModelAndView test(ModelAndView mav, @RequestParam(defaultValue = "1") int time) {
        try {
            Thread.sleep(1000 * time);
        } catch (Exception e) {
        }
        mav.setViewName("success.html");
        return mav;
    }

    /**
     * test访问熔断后回调页面
     * 
     * @param mav
     * @param time
     * @return
     */
    protected ModelAndView testFallback(ModelAndView mav, @RequestParam(defaultValue = "1") int time) {
        mav.setViewName("fallback.html");
        return mav;
    }
}

4、在webapp目录下添加fallback.html、success.html文件

5、访问http://127.0.0.1:8080/spring-hystrix-demo/test?time=0,浏览器正常进入success.html页面;

      访问http://127.0.0.1:8080/spring-hystrix-demo/test?time=5,连接超时,后台执行testFallback方法,浏览器进入fallback.html页面。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值