参考
1.依赖pom.xml
4.0.0 com.guo guo 0.0.1-SNAPSHOT guo-gateway org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.cloud spring-cloud-starter-gateway
2.配置application.yml
server: port: 8081spring: application: name: guo-gateway cloud: gateway: discovery: locator: enabled: false lowerCaseServiceId: true eureka: client: service-url: defaultZone: http://localhost:8761/eureka/logging: level: org.springframework.cloud.gateway: debug
3.启动配置
package com.guo.gateway;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.gateway.route.RouteLocator;import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;import org.springframework.context.annotation.Bean;@SpringBootApplication@EnableEurekaClientpublic class Application { public static void main(String[] args) { SpringApplication.run( Application.class, args ); } @Bean public RouteLocator myRoutes(RouteLocatorBuilder builder) { String httpUri = "http://localhost:8762/hi"; return builder.routes() .route(p -> p .path("/demo") .filters(f -> f.addRequestHeader("Hello", "World")) .uri(httpUri)) .build(); }}
4.启动演示
启动eureka-server eureka-client gateway
访问gateway接口 会自动转发到
5.添加熔断器
pom.xml
org.springframework.cloud spring-cloud-starter-netflix-hystrix
添加过滤器
package com.guo.gateway;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.gateway.route.RouteLocator;import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;import org.springframework.context.annotation.Bean;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import reactor.core.publisher.Mono;@SpringBootApplication@EnableEurekaClient@RestControllerpublic class Application { public static void main(String[] args) { SpringApplication.run( Application.class, args ); } @Bean public RouteLocator myRoutes(RouteLocatorBuilder builder) { String httpUri = "http://localhost:8762/hi"; return builder.routes() .route(p -> p .path("/demo") .filters(f -> f.addRequestHeader("Hello", "World")) .uri(httpUri)) .route(p -> p .path("/hystrix") .filters(f -> f .hystrix(config -> config .setName("mycmd") .setFallbackUri("forward:/fallback"))) .uri(httpUri)) .build(); } @RequestMapping("/fallback") public Monofallback() { return Mono.just("fallback"); }}
停掉 http://localhost:8762/hi 服务,访问熔断成功。