springcloudgateway集成hystrix ⽬录
springcloudgateway集成hystrix⾮常简单,官⽹的说明很清晰明了。
⼀,pom引⼊依赖。
<!-- 熔断和限流 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
⽹关中⽤到了ribbon,
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
⼆,RestTemplate开启ribbon的负载均衡,@LoadBalanced fig;
import java.nio.chart.Chart;
htl
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.verter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
/
/ample.gate.rvice.DbRouteDefinitionRepository;
//fig.CommonClientConfigKey
//flix.loadbalancer.RetryRuleorgy
/**
* 这个配置类是公共的配置。
* 如果某⼀项配置信息⽐较多,就单独弄⼀个配置类。
*
*
* @author lsy
*
*/
@Configuration
public class GateConfig {
@Bean
bred@LoadBalanced
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
// ⽀持中⽂编码
return restTemplate;
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
// SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.tReadTimeout(5000);// 单位为ms
httpRequestFactory.tConnectTimeout(5000);// 单位为ms
return httpRequestFactory;
}
// @Bean
// public RestTemplate restTemplate(RestTemplateBuilder builder){
// return builder.build();
// }
// @Bean
// public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
// utes()
// .route("path_route", r -> r.path("/get")
// .uri(""))
//
// .route("host_route", r -> r.host("*.")
// .uri(""))
//
// .route("rewrite_route", r -> r.host("*.")
// .filters(f -> f.rewritePath("/foo/(?<gment>.*)", "/${gment}"))
/
/ .uri(""))
//
// .route("hystrix_route", r -> r.host("*.")
// .filters(f -> f.hystrix(c -> c.tName("slowcmd")))
// .uri(""))
//
// .route("hystrix_fallback_route", r -> r.host("*.")
// .filters(f -> f.hystrix(c -> c.tName("slowcmd").tFallbackUri("forward:/hystrixfallback")))
// .uri(""))
//
// .route("limit_route", r -> r
/
/ .host("*.").and().path("/anything/**")
// .filters(f -> f.requestRateLimiter(c -> c.tRateLimiter(redisRateLimiter())))
// .uri(""))
//
// .build();
// }
// @Bean
// public RouteDefinitionWriter routeDefinitionWriter() {
// return new InMemoryRouteDefinitionRepository();
// }
//
/
/ @Bean
// public DbRouteDefinitionRepository dbRouteDefinitionRepository() {
// return new DbRouteDefinitionRepository();
// }
}
三,yml配置和熔断降级的fallback接⼝。
ample.gate.hystrix;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponBody;
import org.springframework.web.bind.annotation.RestController;
publisher.Mono;
/**
* HystrixGatewayFilterFactory
* HystrixCommandProperties
*
* Resilience4JCircuitBreakerFactory
* ReactiveResilience4JCircuitBreakerFactory
*
* 默认降级处理。
* 当请求在⼀定时间内没有返回就出发⽹关的熔断,进⾏降级处理。
* 即:请求被替换成这个熔断降级的controller,返回的内容就是这个controller的返回。 * 这个写在⽹关⾥。
*
*/
@RestController
public class DefaultHystrixController {
Logger logger = Logger(DefaultHystrixController.class);
@RequestMapping("/defaultfallback")
@ResponBody
public Map<String, String> defaultfallback() {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss SSS"); String w().format(df);
我回来了英文logger.info("DefaultHystrixController降级操作...defaultfallback");
Map<String, String> map = new HashMap<>();
map.put("resultCode", "fail");
map.put("resultMessage", "服务繁忙,请稍后重试defaultfallback");
map.put("time", dateNowStr);
return map;
}
@RequestMapping("/defaultfallback1")
@ResponBody
public Map<String, String> defaultfallback1() {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss SSS"); String w().format(df);
logger.info("DefaultHystrixController降级操作...defaultfallback111111");
Map<String, String> map = new HashMap<>();
map.put("resultCode", "fail");
map.put("resultMessage", "服务繁忙,请稍后重试defaultfallback111111");
map.put("time", dateNowStr);
return map;
}
@GetMapping(value="/defaultfallback2")
public Map<String, String> defaultfallback2() {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss SSS"); String w().format(df);
logger.info("DefaultHystrixController降级操作...defaultfallback222222");
Map<String, String> map = new HashMap<>();
map.put("resultCode", "fail");
map.put("resultMessage", "服务繁忙,请稍后重试defaultfallback222222");
map.put("time", dateNowStr);
map.put("time", dateNowStr);
return map;
}
// @RequestMapping("/defaultfallback3")
// public Mono<String> defaultfallback3() {
// return Mono.just("defaultfallback3");
六级英语作文万能模板
// }
}
yml:
rver:
port: 8888
#链接建⽴超时时间
connection-timeout: 10000
tomcat:
max-threads: 6 # 最⼤线程数
min-spare-thread: 3 # 最⼩线程数
accept-count: 10 # 队列长度
max-connections: 1000 # 最⼤链接数
spring:
application:
name: gate
rvlet:
multipart:
max-file-size: 50MB #单个⽂件上传的⼤⼩限制,默认1MB
led是什么意思
max-request-size: 150MB #⼀次请求总共⽂件⼤侠限制。如果⽤nginx,需要改nginx的限制,在rver配置client_max_body_size 300M;
redis:
timeout: 6000ms
databa: 10
host: localhost #单实例redis⽤这个配置
password: #单实例redis⽤这个配置
port: 6379 #单实例redis⽤这个配置
# password: Redis@123 #集群⽤这个配置
# cluster: #集群⽤这个配置
# nodes:
# - 127.0.0.1:7011
# - 127.0.0.1:7012
# - 127.0.0.1:7013
# - 127.0.0.1:7014
# - 127.0.0.1:7015
# - 127.0.0.1:7016
# max-redirects: 2 #获取失败最⼤重定向次数
lettuce:
pool:
max-active: 1000 #连接池最⼤连接数(使⽤负值表⽰没有限制)
max-idle: 10 #连接池中的最⼤空闲连接
min-idle: 3 #连接池中的最⼩空闲连接
max-wait: -1 #连接池最⼤阻塞等待时间(使⽤负值表⽰没有限制)
cloud:
consul:
host: 127.0.0.1 #注册中⼼的ip或host。也是集群地址,配置⼀个即可。注释掉整个consul这段就可以启动,即使没有注册中⼼也不报错。有这段就必须有⼀个可⽤ port: 8500
discovery:
enabled: true #默认true。Consul Discovery Client是否注册到注册中⼼。和register同时设置成fal,就不需要起consul服务。
register: true #是否将服务注册到Consul集群中⼼.。这个参数和上⾯的enabled参数同时设置成fal,应⽤才不会注册注册中⼼,才可以不起consul服务!
deregister: true #默认true,服务停⽌时注销服务,即从服务列表中删除。设置成fal的话,
#rvice-name: ${spring.application.name} #注册在consul上⾯的名字,在consul的调⽤中,是通过此名字调⽤的。默认服务名,不要改
instance-id: ${spring.application.name}-${spring.cloud.client.ip-address}:${rver.port} #只供显⽰⽤,在ID列显⽰same to you
health-check-interval: 10s #配置 Consul 健康检查频率,也就是⼼跳频率。
health-check-timeout: 10s #健康检查超时
# health-check-critical-timeout: 10s #注册成功之后,如果关闭微服务,consul将检测60s,如果60s之后还检测不到此服务,将会把此服务从注册列表中移除.如果想 #health-check-path: /tmp #健康检查路径
prefer-ip-address: true #表⽰注册时使⽤IP⽽不是hostname
retry:
initial-interval: 1000 # 初始重试间隔(以毫秒为单位
max-attempts: 3
max-interval: 2000
multiplier: 1.1
gateway:
# default-filters:
# - name: Hystrix
# args:
# name: myfallback
# fallbackUri: forward:/defaultfallback
routes:
- id: one
uri: lb://one
predicates:
-
Path=/one/**dfx
filters:
- StripPrefix=1
- AddRequestHeader=X-Request-color, blue
- AddRequestHeader=X-Request-temp, blue2012湖北高考英语
- name: RequestRateLimiter
args:
rate-limiter: "#{@urlAndChannelRedisRateLimiter}"
培训费查询key-resolver: "#{@lfUrlAndChannelKeyResolver}"
- name: Hystrix
args:
name: commandone
fallbackUri: forward:/defaultfallback1
- id: two
uri: lb://two
predicates:
- Path=/two/**
filters:
- StripPrefix=1
- name: RequestRateLimiter
args:
rate-limiter: "#{@urlAndChannelRedisRateLimiter}"
key-resolver: "#{@lfUrlAndChannelKeyResolver}"
- name: Hystrix
args:
name: commandtwo
fallbackUri: forward:/defaultfallback2
# hystrix 信号量隔离,timeoutInMilliconds毫秒后⾃动超时.第3个值跟Hystrix的name属性是对应的。⽐如,你配置的是fallbackone,name就该这样配置fallbackone
hystrix:
threadpool:
default:
coreSize: 10
maxQueueSize: -1
queueSizeRejectionThreshold: 1000
command:
myfallback:
metrics:
rollingStats:
timeInMilliconds: 10000 #默认10000即10秒
execution:
isolation: