前置:配置注册中心
https://yjtzfywh.blog.csdn.net/article/details/129220590
微服务网关是介于客户端和服务器端之间的中间层,所有的外部请求都会先经过微服务网关。
一、导入依赖
<dependencies> <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> </dependencies>
二、配置文件
server: port: 8500 eureka: client: service-url: defaultZone: http://localhost:8801/eureka, http://localhost:8802/eureka spring: application: name: gateway cloud: gateway: routes: - id: borrow-service uri: lb://borrowservice predicates: - Path=/borrow/** # 继续添加新的路由配置,这里就以书籍管理服务为例 # 注意-要对齐routes: - id: book-service uri: lb://bookservice predicates: - Path=/book/** filters: # 添加过滤器 - AddRequestHeader=Test, HelloWorld! # AddRequestHeader 就是添加请求头信息,其他工厂请查阅官网
三、启动类
package com.minos; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class GateWayServerApplication { public static void main(String[] args) { SpringApplication.run(GateWayServerApplication.class, args); } }
四、自定义全局路由过滤
1.import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; import java.util.List; @Component //需要注册为Bean public class TestFilter implements GlobalFilter, Ordered {//指定过滤器之间的顺序 @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { //只需要实现此方法 //先获取ServerHttpRequest对象,注意不是HttpServletRequest ServerHttpRequest request = exchange.getRequest(); //打印一下所有的请求参数 System.out.println(request.getQueryParams()); //判断是否包含test参数,且参数值为1 ?test=1 List<String> value = request.getQueryParams().get("test"); if (value != null && value.contains("1")) { //将ServerWebExchange向过滤链的下一级传递(跟JavaWeb中介绍的过滤器其实是差不多的) return chain.filter(exchange); } else { //直接在这里不再向下传递,然后返回响应 return exchange.getResponse().setComplete(); } } /** * 注意Order的值越小优先级越高, * 并且无论是在配置文件中编写的单个路由过滤器还是全局路由过滤器,都会受到Order值影响 * * @return */ @Override public int getOrder() { return 0; } }
五、测试
启动服务,注册中心注册正常。
通过注册中心访问
http://localhost:8500/borrow/1?test=1 { "user": { "uid": 1, "name": "小明", "sex": "男" }, "bookList": [ { "bid": 1, "title": "深入理解Java虚拟机", "desc": "讲解JVM底层原理" }, { "bid": 2, "title": "Java并发编程的艺术", "desc": "讲解并发编程的各种技术" } ] }
直接访问
http://localhost:8301/borrow/1 { "user": { "uid": 1, "name": "小明", "sex": "男" }, "bookList": [ { "bid": 1, "title": "深入理解Java虚拟机", "desc": "讲解JVM底层原理" }, { "bid": 2, "title": "Java并发编程的艺术", "desc": "讲解并发编程的各种技术" } ] }