hebe,木府风云,米线的做法-秘密素材库,素材库专家

admin 1个月前 ( 11-01 08:22 ) 0条评论
摘要: 1. Sentinel整合Feign和RestTemplateSentinel目前已经同时支持Feign和RestTemplate,需要我们引入对应的依赖,在使用Feign的时候需...

1. Sentinel整合Feign和RestTemplate

Sentinel现在现已一起支撑Feign和RestTemplate,需求咱们引进对应的依靠,在运用Feign的时分需求在装备文件中翻开Sentinel对Feign的支撑:feign.sentinel.enabled=true,一起需求参加openfeign starter依靠使sentinel starter中的自动化装备类收效。在运用RestTemplate的时分需求在结构RestTemplate的Bean的时分加上@SentinelRestTemplate注解,敞开Sentinel对RestTemplate的支撑。

1.1 创立父工程sentinel-springcloud-high:

父工程pom.xml如下:

代码清单:Alibaba/sentinel-springcloud-high/pom.xml

***


org.springframework.boot
spring-boot-starter-actuator


org.springframework.boot
spring-boot-starter-web


com.alibaba.cloud
spring-cloud-starter-alibaba-sentinel


com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery

公共组件中引进Sentinel做流量操控,引进Nacos做服务中心。

1.2 创立子工程provider_server:

装备墨痕黄宗泽文件application.yml如下:

代码清单:Alibaba/sentine姚慧汶l-springcloud-high/provider_server/pom.xml

***

server:
port: 8000
spring:
application:
name: spring-cloud-provider-server
cloud:
nacos:
discovery:
server-addr: 192.168.44.129:8848
sentinel:
transport:
dashboard: localhost:8080
port: 8720
management:
endpoints:
web:
cors:
allowed-methods: '*'

接口测验类HelloController.java如下:

代码清单:Alibaba/sentinel-springcloud-high/provider_server/src/main/java/com/springcloud/provider_server/controller/HelloController.java

***

@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(HttpServletRequest request) {
return "Hello, port is: " + request.getLocalPort();
}
}萝莉在线观看

1.3 创立子工程consumer_server:

子工程依靠pom.xml如下:

代码清单:Alibaba/sentinel-springcloud-high/consumer_server/pom.xml

***


org.springframework.cloud
spring-cloud-starter-openfeign

装备文件application.yml如下:

代码清单:Alibaba/sentinel-springcloud-high/consumer_server/src/main/resources/application.yml

***

server:
port: 9000
spring:
application:
name: spring-cloud-consumer-server
cloud:
nacos:
discovery:
server-addr: 192.168.44.129:8848
sentinel:
transport:
dashboard: localhost:8080
port: 8719
management:
endpoints:
web:
cors:
allowed-methods: '*'
feign:
sentinel:
enabled: true

这儿运用feign.sentinel.enabled=true敞开Sentinel对Feign的支撑。

接口测验类HelloController.java

代码清单:Alibaba/sentinel-springcloud-high/consumer_server/src/main/java/com/springcloud/consumer_server/controller/HelloController.java

***

@RestController
public class HelloController {学校寻美记
@Autowired
HelloRemote helloRemote;
@Autowired
RestTemplate restTemplate;
@GetMapping("/helloByFeign")
public String helloByFeign() {
return helloRemote.hello();
}
@GetMapping("/helloByRestTemplate")
public String helloByRestTemplate() {
return restTemplate.getForObject("http://spring-cloud-provider-server/hello/", String.class);
}
}

Sentinel现已对做了整合,咱们运用Feign的当地无需额定的注解。一起,@FeignClient注解中的一切特点,Sentinel都做了兼容。

发动主类Ch122ConsumerServerApplication.java如下:

代码清单:Alibaba/sentinel-springcloud-high/consumer_server/src/main/java/com/springcloud/consumer_server/ConsumerServerApplication.java

***

@S阮灶新pringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class Ch122ConsumerServerApplication {
public static void main(String[] args) {
SpringApplication.run(Ch122ConsumerServerApplication.class, args);
}
@Bean
@LoadBalanced
@SentinelRestTemplate
public RestTemplate restTemplate() {
return new RestTemplate();
}
}

在运用RestTemplate的时分需求添加@SentinelRestTemplate来敞开Sentinel对RestTemplate的支撑。

1.4 测验

发动工程provider_server和consumer_server,provider_server修正发动装备,发动两个实例,翻开浏览器拜访:http://localhost:9000/helloByFeign 和 http://localhost:9000/helloByRestTemplate ,改写几回,能够看到页面替换显现Hello, port is: 8000和Hello, port is: 8001,阐明现在负载均衡正常,现在检查Sentinel操控台,如图:

1.5 流量操控测验

这时挑选左边的簇点流控,点击流控,如图:

这儿咱们装备一个最简略的规矩,装备QPS限制为1,点击新增,如图:

这儿解释一下什么是QPS,简略来说QPS是一个每秒拜访数,这儿咱们测验时需求重复快速改写http://localhost:9000/helloByFeign 和 http://localhost:9000/helloByRestTemplate ,在改写的过程中,咱们能够看到页面会显现错误信息,如:Blocked by Sentinel (flow limiting),阐明咱们装备Sentinel现已限流成功,这时咱们再看一下Sentinel的操控台,能够看到咱们方才拜访的成功和限流的数量,如图:

2. 服务降级

在上一小结,咱们介绍了Feign和RestTemplate整合Sentinel运用,而且在Sentinel操控台上做了QPS限流,而且限流成功,限流成功后,默许状况下,Sentinel对操控资源的限流处理是直接抛出反常。在没有合理的事务接受或许前端对接状况下能够这样,可是正常状况为了更好的用户事务,都会完结一些被限流之后的特别处理,咱们不期望展现一个僵硬的报错。这一末节,咱们介绍一下服务降级处理。

2.1 创立子工程consumer_fallback

Feign服务降级类HelloRemoteFallBack.java如下:

代码清单:Alibaba/sentinel-springc公务攻办loud-high/consumer_fallback/src/main/java/com/springcloud/consumer_fallback/fallback/HelloRemoteFallBack.java

***

@Component
public class HelloRemoteFallBachebe,木府风云,米线的做法-隐秘素材库,素材库专家k implements HelloRemote {
@Override
public String hello() {
return "Feign FallBack Msg";
}
}

相对应的,这儿需求在HelloRemote.java上做一部分装备,使得限流后,触发服务降级履行咱们的服务降级类,代码如下:

代码清单:ch12_2/ch12_2_consumer_fallback/src/main/java/com/springcloud/book/ch12_2_consumer_fallback/remote/HelloRemote.java

***

@FeignClient(name = "spring-cloud-provider-server", fallback = HelloRemoteFallBack.class)
public interface HelloRemote {
@GetMapping("/hello")
String hello();
}

fallback = HelloRemoteFallBack.class指定服务降级的处理类为HelloRemoteFallBack.class。

RestTemplate服务降级东西类ExceptionUtil.java如下:

代码清单:Alibaba/sentinel-springcloud-high/consumer_fallback/src/main/java/com/springcloud/consumer_fallback/remote/HelloRemote.java

***

public class ExceptionUtil {
private final static Logger logger = LoggerFactory.getLogger(ExceptionUtil.class);
public static SentinelClientHttpResponse handleException(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException ex) {
logger.error(ex.getMessage(), ex);
return new SentinelClientHttpResponse("RestTemplate FallBack Msg");
}
}

这儿相同需求修正RestTemplate注册成为Bean的当地,使得RestTemplate触发服务降级今后代码履行咱们为它写的处理类,Ch122ConsumerFallbackApplication.java代码如下:

代码清单:Alibaba/sentinel-springcloud-high/consumer_fallback/src/main/java/com/springcloud/consumer_fallback/ConsumerFallbackApplication.java

***

@Bean
@LoadBalanced
@SentinelRestTemplate(blockHandler = "handleException", blockHandlerClass = ExceptionUtil.class)
public RestTemplate restTemplate() {
return new RestTemplate();
}

这儿需求留意,@SentinelRestTemplate注解的特点支撑限流(blockHandler, blockHandlerClass)和降级(fallback, fallbackClass)的处理。

其间blockHandler或fallback特点对应的办法有必要是对应blockHandlerClass或fallbackClass特点中的静态办法。

@SentinelRestTemplate注解的限流(blockHandler, blockHandlerClass)和降级(fallback, fallbackClass)特点不强制填写。

当运用RestTemplate调用被Sentinel熔断后,会回来RestTemplate request block by sentinel信息,或许也能够编写对应的办法自行处理回来信息。这儿供给了 SentinelClientHttpResponse用于结构回来信息。

2.2 测验

依次发动provider_server和consumer_fallback两个子工程。先在浏览器中替换拜访http://localhost:9090/helloByFeign 和 http://localhost:9090/helloByRestTemplate ,然后翻开Sentinel操控台,在这两个接口上添加限流信息,留意,这儿要将限流信息加在资源上,详细如图:

在浏览器中改写两个链接,两个限流信息都能够正常浏览器中显现,测验成功,再次检查Sentinel操控台,也能够看到被拒接的流量计算,如图:

3. Sentinel整合服务网关限流

Sentinel现在支撑Spring Cloud Gateway、Zuul 等干流的 API Gateway 进行限流。看一下官方的结构图,如图:

从这张官方的图中,能够看到,Sentinel对Zuul的限流主要是经过3个Filter来完结的,对Spring Cloud Gateway则是经过一个SentinleGatewayFilter和一个BlockRequestHandler来完结的。

Sentinel 1.6.0 引进了 Sentinel API Gateway Adapter Common 模块,此模块中包括网关限流的规矩和自界说 API 的实体和办理逻辑:

  • GatewayFlowRule:网关限流规矩,针对 API Gateway 的场景定制的限流规矩,能够针对不同 route 或自界说的 API 分组进行限流,支撑针对恳求中的参数、Header、来历 IP 等进行定制化的限流。
  • ApiDefinition:用户自界说的 API 界说分组,能够看做是一些 URL 匹配的组合。比方咱们能够界说一个 API 叫 my_api,恳求 path 形式为 /foo/** 和 /baz/** 的都归到 my_api 这个 API 分组下面。限流的时分能够针对这个自界说的 API 分组维度进行限流。

3.1 Zuul 1.x

Sentinel 供给了 Zuul 1.x 的适配模块,能够为 Zuul Gateway 供给两种资源维度的限流:

  • route 维度:即在 Spring 装备文件中装备的路由条目,资源名为对应的hebe,木府风云,米线的做法-隐秘素材库,素材库专家 route ID(对应 RequestContext 中的 proxy 字段)
  • 自界说 API 维度:用户能够使用 Sentinel 供给的 API 来自界说一些 API 分组

3.1.1 创立子工程zuul_server

工程依靠pom.xml如下:

代码清单:Alibaba/sentinel-springcloud-high/zuul_server/pom.xml

***


o柯德来rg.springframework.cloud
spring-cloud-starter-netflix-zuul


com.alibaba.csp
sentinel-zuul-adapter

这儿由于sentinel-zuul-adapter未包括在spring-cloud-starter-alibaba-sentinel,需求手动独自引进。

3.1.2 装备文件application.yml如下:

代码清单:Alibaba/sentinel-springcloud-high/zuul_server/src/main/resources/application.yml

***

server:
port: 18080
spring:
application:
name: spring-cloud-zuul-hebe,木府风云,米线的做法-隐秘素材库,素材库专家server
cloud:
nacos:
discovery:
server-addr: 192.168.44.129:8848
sentinel:
transport:
dashboard: localhost:8080
port: 8720
zuul:
routes:
consumer-route:
path: /consumer/**
serviceId: spring-cloud-consumer-fallback

3.1.3 界说降级处理类ZuulFallbackProvider.java如下:

代码清单:Alibaba/se应试宝官网ntinel-springcloud-high/zuul_server/src/main/java/com/springcloud/zuul_server/fallback/ZuulFallbackProvider.java

***

public class ZuulFallbackProvider implements ZuulBlockFallbackProvidehebe,木府风云,米线的做法-隐秘素材库,素材库专家r {
@Override
public String getRoute() {
return "*";
}
@Override
public BlockResponse fallbackResponse(String route, Throwable cause) {
RecordLog.info(String.format("[Sentinel DefaultBlockFallbackProvider] Run fallback route: %s", route));
if (cause instanceof BlockException) {
return new BlockResponse(429, "Sentinel block exception", route);
} else {
return new BlockResponse(500, "System Error", route);
}
}
}

3.1.4 一起,咱们需求将3个Sentinel的Filter注入Spring,装备类如下:

代码清单:Alibaba/sentinel-springcloud-high/zuul_server/src/main/java/com/springcloud/zuul_server/config/ZuulConfig.java

***

@Configuration
public class ZuulConfig {
@Bean
public ZuulFilter sentinelZuulPreFilter() {
// We can also provider the filter order in the constructor.
return new SentinelZuulPreFilter();
}
@Bean
public ZuulFilter sentinelZuulPostF圆圆大光头ilter() {
return new SentinelZuulPostFilter();
}
@Bean
public ZuulFilter sentinelZuulErrorFilter() {
return new SentinelZuulErrorFilter();
}
/**
* 注册 ZuulFallbackProvider
*/
@PostConstruct
public void doInit() {
ZuulBlockFallbackManager.registerProvider(new ZuulFallbackProvider());
}
}

终究,发动前需求装备JVM发动参数,添加-Dcsp.sentinel.app.type=1,来告知Sentinel操控台咱们发动的服务是为 API Gateway 类型。

3.1.5 测验

依次发动子工程provider_server、consumer_fallback、zuul_server,翻开浏览器拜访:http://localhost:18080/consumer/helloByFeign ,然后咱们翻开Sentinel操控台,检查zuul_server服务,如图:

咱们定制限流战略,依旧是QPS为1,咱们再次改写http://localhost:18080/consumer/helloByFeign 页面,这时,页面上现已能够正产限流了,限流后显现的内容为:

{"code":429, "message":"Sentinel block exception", "route":"consumer-route"}

这儿留意,界说限流的是资源,千万不要界说错当地,限流界说如图:

3.2 Spring Cloud Gateway

从 1.6.0 版别开端,Sentinel 供给了 Spring Cloud Gateway 的适配模块,能够供给两种资源维度的限流:

  • route 维度:即在 Spring 装备文件中装备的路由条目,资源名为对应的 routeId
  • 自界说 API 维度:用户能够使用 Sentinel 供给的 API 来自界说一些 API 分组

3.2.1 创立子工程gateway_server

工程依靠pom.xml如下:

代码清单:Alibaba/sentinel-springcloud-high/gateway_server/pom.xml

***


org.springframework.boot
spring-boot-starter-webflux


org.springframework.cloud
spring-cloud-starter-gateway


com.alibaba.csp
sentinel-spring-cloud-gateway-adapter

3.2.2 装备文件application.yml如下:

代码清单:Alibaba/sentinel-springcloud-high/gateway_server/src/main/resources/application.yml

***

server:
port: 28080
spring:
application:
name: spring-cloud-gateway-server
cloud:
nacos:
discovery:
server-addr: 192.168.44.129:8848
sentinel:
transport:
dashboard: localhost:8080
port: 8720
gateway:
enabled: true
discovery:
locator:
lower-case-service-id: true
routes:
- id: consumer_server
uri: lb://spring-cloud-consuhebe,木府风云,米线的做法-隐秘素材库,素材库专家mer-fallback
predicates:
- Method=GET

3.2.3 大局装备类GatewayConfig.java如下:

同上一末节介绍的Zuul,这儿咱们相同需求将两个Sentinel有关Spring Cloud Gateway的Filter注入Spring:SentinelGatewayFilter和SentinelGatewayBlockExceptionHandler,这儿由于在Sentinel v1.6.0版别才参加Spring Cloud Gateway的支撑,许多当地还不是很完善,反常处理SentinelGatewayBlockExceptionHandler现在只能回来一个反常信息,在咱们的体系中无法和上下游很好的结合,这儿笔者自己从头完结了SentinelGatewayBlockExceptionHandler,并命名为JsonSentinelGatewayBlockExceptionHandler,回来参数界说成为JSON,这儿不再注入Sentinel供给的SentinelGatewayBlockExceptionHandler,而是改为笔者自己完结的JsonSentinelGateway张嘉译前妻杜珺相片BlockExceptionHandler。

代码清单:Alibaba/sentinel-springcloud-high/gateway_server/src/main/java/com/springcloud/gateway_server/config/GatewayConfig.java

***

@Configuration
public class GatewayConfig {
private final List viewResolvers;
private final ServerCodecConfigurer serverCohebe,木府风云,米线的做法-隐秘素材库,素材库专家decConfigurer;
public GatewayConfig(ObjectProvirapevideoder> viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer) {
this.viewResolvers = viewResolversProvider.getIfAva看护甜心之冰蓝蝴蝶ilable(Collections::emptyList);
this.serverCodecConfigurer = serverCodecConfigurer;
}
@Bean奉仕
@Ord清客云控er(Ordered.HIGHEST_PRECEDENCE)
public JsonSentinelGatewayBlockExceptionHandler jsonSentinelGatewayBlockExceptionHandler() {
// Register the block exception handler for Spring Cloud Gateway.
return new JsonSentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
}
@Bean
@Order(-1)
public GlobalFilter sentinelGatewayFilter() {
return new SentinelGatewayFilter();
}
}

3.2.4 降级处理类JsonSentinelGatewayBlockExceptionHandler.java如下:

代码清单:Alibaba/sentinel-springcloud-high/gateway_server/src/main/java/com/springcloud/gate佳人入肉way_server/exception/JsonSentinelGatewayBlockExceptionHandler.java

***

public class JsonSentinelGatewayBlockExceptionHandler implements WebExceptionHandler {
private List viewResolvers;
private List
public JsonSentinelGatewayBlockExceptionHandler(List viewResolvers, ServerCodecConfigurer serverCodecConfigurer) {
this.viewResolvers = viewResolvers;
this.messageWriters = serverCodecConfigurer.getWriters();
}
private Mono writeResponse(ServerResponse response, ServerWebExchange exchange) {
ServerHttpResponse serverHttpResponse = exchange.getResponse();
serverHttpResponse.getHeaders().add("Content-Type", "application/jso张嘉译前妻杜珺相片n;charset=UTF-8");
byte[] datas = "{\"code\":403,\"msg\":\"Sentinel block exception\"}".getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = serverHttpResponse.bufferFactory().wrap(datas);
return serverHttpResponse.writeWith(Mono.just(buffer));
}
@Override
public Mono handle(ServerWebExchange exchange, Throwable ex) {
if (exchange.getResponse().isCommitted()) {
return Mono.e张林谈家电rror(ex);
}
// This exception handler only handles rejection by Sentinel.
if (!BlockException.isBlockException(ex)) {
return Mono.error(ex);
}
return handleBlockedRequest(exchange, ex)
.flatMap(response -> writeResponse(response, exchange));
}
private Mono handleBlockedRequest(ServerWebExchange exchange, Throwable throwable) {
return GatewayCallbackManager.getBlockHandler().handleRequest(exchange, throwable);
}
private final Supplier contextSupplier = () -> new ServerResponse.Context() {
@Override
public List
return JsonSentinelGatewayBlockExceptionHandler.this.messageWriters;
}
@O丁水妹verride
public List viewResolvers() {
return JsonSentinelGatewayBlockExceptionHandler.this.viewResolvers;
}
};
}

笔者这儿仅重写了writeResponse()办法,讲回来信息简略的更改成了json格局,各位读者有需求能够依据自己的需求进行修正。

3.2.5 测验

依次发动provider_server、consumer_server和gateway_server,装备gateway_server jvm发动参数-Dcsp.sentinel.app.type=1,如图:

翻开浏览器拜访:http://localhost:28080/helloByFeign ,改写几回,页面正常回来Hello, port is: 8000,翻开Sentinel操控台,装备限流战略,QPS限制为1,再改写浏览器页面,这时,咱们能够看到浏览器回来限迷镇凶案流信息:

{"code":403,"msg":"Senthebe,木府风云,米线的做法-隐秘素材库,素材库专家inel block exception"}

测验成功。

原文:https://www.cnblogs.com/babycomeon/p/11516011.html

作者:极客挖掘机

定时宣布作者的考虑:技能、产品、运营、自我提升等。

文章版权及转载声明:

作者:admin本文地址:http://www.suckercreek.net/articles/4335.html发布于 1个月前 ( 11-01 08:22 )
文章转载或复制请以超链接形式并注明出处秘密素材库,素材库专家