dubbo服务降级(五)
2019-07-29 本文已影响0人
小怪兽打葫芦娃
Dubbo入门案例(一)
Dubbo入门案例(二)
Dubbo入门案例(三)
Dubbo入门案例(四)
Dubbo入门案例(五)
Dubbo入门案例(六)
Dubbo入门案例(七)
Dubbo入门案例(八)
什么是服务降级?
当服务器压力剧增的情况下,根据实际业务情况及流量,对一些服务和页面有策略的不处理或换种简单的方式处理,从而释放服务器资源以保证核心交易正常运作或高效运作。
可以通过服务降级功能临时屏蔽某个出错的非关键服务,并定义降级后的返回策略。
说的直白点就是:比如在公司,咱们领导最喜欢干的事情就是,牺牲基层员工的利益,保住核心领导层的利益
8.3.1 第一种方式实现服务降级
![](https://img.haomeiwen.com/i4037105/11e451ec7e27e101.png)
mock=force:return+null 表示消费方对该服务的方法调用都直接返回 null 值,不发起远程调用。用来屏蔽不重要服务不可用时对调用方的影响。
还可以改为 mock=fail:return+null 表示消费方对该服务的方法调用在失败后,再返回 null 值,不抛异常。用来容忍不重要服务不稳定时对调用方的影响。
![](https://img.haomeiwen.com/i4037105/1a51a87a3b1117b4.png)
启动一个提供者,启动一个消费者
![](https://img.haomeiwen.com/i4037105/45e94b35501306c8.png)
请求:
![](https://img.haomeiwen.com/i4037105/b6c305a880b70e8b.png)
重新开启消费者:
![](https://img.haomeiwen.com/i4037105/9ff37f57f2f4ca16.png)
请求:
![](https://img.haomeiwen.com/i4037105/267322cdda41d0a4.png)
8.3.2 第二种方式实现服务降级
修改工程dubbodemo_consumer,里面的@Reference注解,设置超时时间
package com.maweiqi.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.maweiqi.service.HelloService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* HelloController
*
* @Author: 马伟奇
* @CreateTime: 2019-07-19
* @Description:
*/
@Controller
@RequestMapping("/demo")
public class HelloController {
@Reference(loadbalance = "random",timeout = 1000)
private HelloService helloService;
@RequestMapping("/hello")
@ResponseBody
public String getName(String name){
//远程调用
String result = helloService.sayHello(name);
System.out.println(result);
return result;
}
}
package com.maweiqi.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.maweiqi.service.HelloService;
import org.springframework.transaction.annotation.Transactional;
/**
* HelloServiceImpl
*
* @Author: 马伟奇
* @CreateTime: 2019-07-18
* @Description:
*/
@Service
@Transactional
public class HelloServiceImpl implements HelloService {
@Override
public String sayHello(String name) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "8082 hello " + name;
}
}
![](https://img.haomeiwen.com/i4037105/9a72d59951eff961.png)