39、微服务GateWay 新一代网关
1、SpringCloud gateway三个重要的概念:路由,断言 、过滤
2、创建cloud-gateway-gateway9527 项目编写pom.xml添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>com.atguigu.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
编写application.yml配置文件
server: port: 9527 spring: application: name: cloud-gateway cloud: gateway: routes: - id: payment-routh01 uri: http://localhost:8001 predicates: - Path=/payment/get/** - id: payment-routh02 uri: http://localhost:8001 predicates: - Path=/payment/lb/** eureka: instance: hostname: cloud-gateway-service client: register-with-eureka: true fetch-registry: true service-url: # defaultZone: http://localhost:7001/eureka defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
编写主启动类
@SpringBootApplication @EnableEurekaClient public class GateWayApplication9527 { public static void main(String[] args) { SpringApplication.run(GateWayApplication9527.class,args); } }
测试cloud-provider-payment8001 服务提供者自测:http://localhost:8001/payment/get/1409365580926001153
测试网关gateway服务地址转发到服务提供者:http://localhost:9527/payment/get/1409365580926001153
2、application.yml配置动态路由
server: port: 9527 spring: application: name: cloud-gateway cloud: gateway: discovery: locator: enabled: true #开启动态路由 routes: - id: payment-routh01 uri: lb://cloud-payment-service predicates: - Path=/payment/get/** - id: payment-routh02 uri: lb://cloud-payment-service predicates: - Path=/payment/lb/** eureka: instance: hostname: cloud-gateway-service client: register-with-eureka: true fetch-registry: true service-url: # defaultZone: http://localhost:7001/eureka defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
3、GateWay 的 Filter 自定义过滤器
@Component @Slf4j public class MyLogGatewayFilter implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { String username = exchange.getRequest().getQueryParams().getFirst("username"); if(username == null) { log.info("*******************非法的请求********************"); exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE); return exchange.getResponse().setComplete(); } return chain.filter(exchange); } @Override public int getOrder() { return 0; } }

浙公网安备 33010602011771号