一、前言
接下来是开展一系列的SpringCloud的学习之旅,从传统的模块之间调用,一步步的升级为SpringCloud模块之间的调用,此篇文章为第十六篇,即使用 Sentinel 实现熔断功能。
二、Ribbon 系列
首先我们新建两个服务的提供者模块cloudalibaba-provider-payment9003 和cloudalibaba-provider-payment9004,这两个模块除了配置文件里面的端口号和主启动类不一样,其他的都一样,我这里只介绍其中一个模块的创建过程,pom.xml 内容如下:
4.0.0
com.springcloud
SpringCloud
1.0-SNAPSHOT
cloudalibaba-provider-payment9003
8
8
UTF-8
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
com.springcloud
cloud-api-commons
${project.version}
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-actuator
org.springframework.boot
spring-boot-devtools
runtime
true
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
服务器托管application.yml 内容如下所示:
server:
port: 9003
spring:
application:
name: nacos-payment-provider
cloud:
nacos:
discovery:
server-addr: localhost:8848 #配置Nacos地址
management:
endpoints:
web:
exposure:
include: '*'
主启动类代码如下:
package com.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain9003
{
public static void main(String[] args) {
SpringApplication.run(PaymentMain9003.class, args);
}
}
对外提供的 controller 代码如下:
package com.springcloud.controller;
import com.springcloud.entities.CommonResult;
import com.springcloud.entities.Payment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
@RestController
public class PaymentController {
@Value("${server.port}")
private String serverPort;
public static HashMap hashMap = new HashMap();
static
{
hashMap.put(1L,new Payment(1L,"28a8c1e3bc2742d8848569891fb42181"));
hashMap.put(2L,new Payment(2L,"bba8c1e3bc2742d8848569891ac32182"));
hashMap.put(3L,new Payment(3L,"6ua8c1e3bc2742d8848569891xt92183"));
}
@GetMapping(value = "/paymentSQL/{id}")
public CommonResult paymentSQL(@PathVariable("id") Long id)
{
Payment payment = hashMap.get(id);
CommonResult result = new CommonResult(200,"from mysql,serverPort: "+serverPort,payment);
return result;
}
}
创建一个服务的消费者模块cloudalibaba-consumer-nacos-order84,pom.xml 内容如下所示:
4.0.0
com.springcloud
SpringCloud
1.0-SNAPSHOT
cloudalibaba-consumer-nacos-order84
8
8
UTF-8
org.springframework.cloud
spring-cloud-starter-openfeign
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
com.alibaba.cloud
spring-cloud-starter-alibaba-sentinel
com.springcloud
cloud-api-commons
${project.version}
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-actuator
org.springframework.boot
spring-boot-devtools
runtime
true
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
application.yml 代码如下所示:
server:
port: 84
spring:
application:
name: nacos-order-consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
sentinel:
transport:
#配置Sentinel dashboard地址
dashboard: localhost:8080
#默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
port: 8719
#消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者)
service-url:
nacos-user-service: http://nacos-payment-provider
# 激活Sentinel对Feign的支持
feign:
sentinel:
enabled: true
主启动类代码如下:
package com.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients
public class OrderNacosMain84
{
public static void main(String[] args) {
SpringApplication.run(OrderNacosMain84.class, args);
}
}
配置类代码如下,使其支持负载均衡
package com.springcloud.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ApplicationContextConfig
{
@Bean
@LoadBalanced
public RestTemplate getRestTemplate()
{
return new RestTemplate();
}
}
业务类 controller 代码如下:
@Slf4j
@RestController
public class CircleBreakerController {
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "fallback") //没有配置
public CommonResult fallback(@PathVariable Long id)
{
CommonResult result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);
if (id == 4) {
throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
}
分别启动两个服务提供者和一个消费者,启动完成后,访问http://localhost:84/consumer/fallback/1,进行测试,多刷新几次,可以看到,服务之间的调用没有任何问题,且负载均衡好用。
当我们访问第四条和第五条数据时,由于我们人为的配置了抛出异常,给用户展示了 error 的界面,效果并不是很好,如下图:
2.1 只配置 fallback
为了解决上面返回给客户不友好的界面,我们可以配置 fallback 属性来解决这个问题,它可以对业务的异常进行兜底,修改CircleBreakerController 类,加上 fallback 属性和其对应的方法,如下:
@Slf4j
@RestController
public class CircleBreakerController {
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
// @SentinelResource(value = "fallback") //没有配置
@SentinelResource(value = "fallback", fallback = "handlerFallback") // fallback 只负责业务异常
public CommonResult fallback(@PathVariable Long id) {
CommonResult result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id);
if (id == 4) {
throw new IllegalArgumentException("IllegalArgumentException,非法参数异常....");
} else if (result.getData() == null) {
throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
public CommonResult handlerFallback(@PathVariable Long id, Throwable e) {
Payment payment = new Payment(id, "null");
return new CommonResult(444, "兜底异常handlerFallback,exception内容 " + e.getMessage(), payment);
}
}
重启模块,当我们再次访问第四条和第五条数据时,效果就很好了,如下图:
2.2 只配置blockHandler
修改CircleBreakerController 类,加上 blockHandler 属性和其对应的方法,如下:
@Slf4j
@RestController
public class CircleBreakerController {
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
// @SentinelResource(value = "fallback") //没有配置
// @SentinelResource(value = "fallback", fallback = "handlerFallback") // fallback 只负责业务异常
@SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler 只负责sentinel控制台配置违规
public CommonResult fallback(@PathVariable Long id) {
CommonResult result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id);
if (id == 4) {
throw new IllegalArgumentException("IllegalArgumentException,非法参数异常....");
} else if (result.getData() == null) {
throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
public CommonResult blockHandler(@PathVariable Long id, BlockException blockException) {
Payment payment = new Payment(id,"null");
return new CommonResult(445,"blockHandler-sentinel限流,无此流水: blockException "+blockException.getMessage(),payment);
}
}
配置完毕后打开 sentinel 的管理界面配置降级规则,如下:
在浏览器访问http://localhost:84/consumer/fallback/4,如果点击一次,返回的还是 java 的运行时异常信息,如下图:
如果多点击几次,则显示的是blockHandler 指定的返回信息,如下图:
2.3 配置 fallback 和blockHandler
若既配置了 fallback,又配置了 blockHandler,又会出现什么效果呢?修改 CircleBreakerController 类,代码如下:
@Slf4j
@RestController
public class CircleBreakerController {
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
// @SentinelResource(value = "fallback") //没有配置
// @SentinelResource(value = "fallback", fallback = "handlerFallback") // fallback 只负责业务异常
// @SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler 只负责sentinel控制台配置违规
@SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler")
public CommonResult fallback(@PathVariable Long id) {
CommonResult result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id);
if (id == 4) {
throw new IllegalArgumentException("IllegalArgumentException,非法参数异常....");
} else if (result.getData() == null) {
throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
// 本例是 fallback
public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {
Payment payment = new Payment(id,"null");
return new CommonResult(444,"兜底异常handlerFallback,exception内容 "+e.getMessage(),payme服务器托管nt);
}
// 本例是 blockHandler
public CommonResult blockHandler(@PathVariable Long id,BlockException blockException) {
Payment payment = new Payment(id,"null");
return new CommonResult(445,"blockHandler-sentinel限流,无此流水: blockException "+blockException.getMessage(),payment);
}
}
在 sentinel 中配置一个限流规则,如下:
在浏览器访问http://localhost:84/consumer/fallback/1,如果点击一次,返回结果如下:
频繁点击,效果如下,可以看到限流效果出现了。
在浏览器访问http://localhost:84/consumer/fallback/4,点击一次,返回结果如下,是 fallback 生效了。
频繁点击,效果如下,可以看到限流效果出现了。
2.4 结论
若 blockHandler 和 fallback 都进行了配置,则被限流降级而抛出 BlockException 时只会进入 blockHandler 处理逻辑。
2.5 忽略属性
假如我有一个异常,我不想让 fallback 方法帮我兜底,我就可以通过配置exceptionsToIgnore 属性来实现,修改CircleBreakerController 类的代码,添加exceptionsToIgnore 属性,如下:
@Slf4j
@RestController
public class CircleBreakerController {
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
// @SentinelResource(value = "fallback") //没有配置
// @SentinelResource(value = "fallback", fallback = "handlerFallback") // fallback 只负责业务异常
// @SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler 只负责sentinel控制台配置违规
@SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler",
exceptionsToIgnore = {IllegalArgumentException.class})
public CommonResult fallback(@PathVariable Long id) {
CommonResult result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id);
if (id == 4) {
throw new IllegalArgumentException("IllegalArgumentException,非法参数异常....");
} else if (result.getData() == null) {
throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
// 本例是 fallback
public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {
Payment payment = new Payment(id,"null");
return new CommonResult(444,"兜底异常handlerFallback,exception内容 "+e.getMessage(),payment);
}
// 本例是 blockHandler
public CommonResult blockHandler(@PathVariable Long id,BlockException blockException) {
Payment payment = new Payment(id,"null");
return new CommonResult(445,"blockHandler-sentinel限流,无此流水: blockException "+blockException.getMessage(),payment);
}
}
在 sentinel 中配置降级规则,如下图:
在浏览器中访问http://localhost:84/consumer/fallback/4,如下图,可以发现,fallback 方法并没有生效,但是限流方法方法生效了
三、Feign 系列
3.1 maven 依赖
首先确保消费者模块cloudalibaba-consumer-nacos-order84 的 pom.xml 中引入了 openFegin 的依赖,如下:
org.springframework.cloud
spring-cloud-starter-openfeign
3.2修改配置文件
接下来需要在 application.yml 中激活 sentinel 对 Feign 的支持,如下:
3.3 相关业务类
编写带有 @FeignClient 注解的业务接口,如下:
package com.springcloud.service;
import com.springcloud.entities.CommonResult;
import com.springcloud.entities.Payment;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(value = "nacos-payment-provider",fallback = PaymentFallbackService.class)
public interface PaymentService
{
@GetMapping(value = "/paymentSQL/{id}")
public CommonResult paymentSQL(@PathVariable("id") Long id);
}
然后编写 fallback 参数指定的的兜底方法的类,代码如下:
package com.springcloud.service;
import com.springcloud.entities.CommonResult;
import com.springcloud.entities.Payment;
import org.springframework.stereotype.Component;
@Component
public class PaymentFallbackService implements PaymentService
{
@Override
public CommonResult paymentSQL(Long id)
{
return new CommonResult(44444,"服务降级返回,---PaymentFallbackService",new Payment(id,"errorSerial"));
}
}
修改CircleBreakerController 类,在里面添加如下的方法:
@Resource
private PaymentService paymentService;
@GetMapping(value = "/consumer/paymentSQL/{id}")
public CommonResult paymentSQL(@PathVariable("id") Long id)
{
return paymentService.paymentSQL(id);
}
不要忘了在启动类上添加启用 Feign 的注解,如下图:
3.4 测试
分别启动cloudalibaba-provider-payment9003 模块和cloudalibaba-consumer-nacos-order84 模块,在浏览器输入:http://localhost:84/consumer/paymentSQL/1,如下图,可以正常的访问:
此时故意关闭 9003 微服务提供者,看 84 消费侧自动降级,会不会被耗死,如下图,可以看到,自动进入到了我们指定的兜底方法里面了。
四、熔断框架比较
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
目录 编辑 1.身份信息认证方面: 2.连接方式方面: 3.端口方面: 4.安全性能方面: 5.性能成本服务器托管网 首先需要先了解什么是http和https。 http全称是超文本传输协议、https全称是安全超文本传输协议,仅仅两字之差区别却非常大,其之…