一 网关的作用
反向代理,鉴权,流量控制,熔断,日志监控等等。
二 创建自定义网关
import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; import java.util.Date; @Component @Slf4j public class MyGateWayFilter implements GlobalFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { log.info("start access gateway: "+new Date()); String token = exchange.getRequest().getQueryParams().getFirst("token"); log.info("token: "+token); if(token == null) { log.info("token不能为空"); exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE); return exchange.getResponse().setComplete(); } return chain.filter(exchange); } @Override public int getOrder() { return 0; } }三 nginx负载均衡到网关
(1).将网关微服务上传到192.168.1.1,192.168.1.2,192.168.1.3 服务器,通过命令启动。
nohup java -jar cloudalibaba-gateway.jar >log.file 2>&1 &
(2). nginx.conf配置文件
upstream 192.168.1.13{ server 192.168.1.1:9004; server 192.168.1.2:9004; server 192.168.1.3:9004; } server { listen 9004; server_name 192.168.1.13; location / { proxy_pass http://192.168.1.13; } }
四 下订单微服务通过网关访问
http://192.168.1.13:9004/order/save?userId=1&productId=1&amount=1&token=1