1

springAlibaba实践(12)----网关配置

 2 years ago
source link: http://www.blogjava.net/zzsuje/archive/2022/05/10/450741.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

springAlibaba实践(12)----网关配置

发送请求需要知道商品服务的地址,如果商品服务器有100服务器,1号掉线后,
还得改,所以需要网关动态地管理,他能从注册中心中实时地感知某个服务上
线还是下线。
请求也要加上询问权限,看用户有没有权限访问这个请求,也需要网关。
所以我们使用spring cloud的gateway组件做网关功能。
网关是请求浏览的入口,常用功能包括路由转发,权限校验,限流控制等。springcloud gateway取代了zuul网关。
三大核心概念:
Route: The basic building block of the gateway. It is defined by an ID, a 
destination URI, a collection of predicates断言, and a collection of filters. 
A route is matched if the aggregate predicate is true.
发一个请求给网关,网关要将请求路由到指定的服务。
路由有id,
目的地uri,
断言的集合,
匹配了断言就能到达指定位置,
Predicate断言:
This is a Java 8 Function Predicate. The input type is a Spring 
Framework ServerWebExchange. This lets you match on anything from the 
HTTP request, such as headers or parameters.就是java里的断言函数,匹配请求里的任何信息,包括请求头等
Filter:
These are instances of Spring Framework GatewayFilter that have been 
constructed with a specific factory. Here, you can modify requests and
responses before or after sending the downstream request.
过滤器请求和响应都可以被修改。
客户端发请求给服务端。中间有网关。先交给映射器,如果能处理就交给handler
处理,然后交给一系列filer,然后给指定的服务,再返回回来给客户端。
12.1 创建模块gulimall-gateway
<dependency>
            <groupId>com.zyn.glmall</groupId>
            <artifactId>glmall-common</artifactId>
            <version>0.0.1-SNAPSHOT</version>
</dependency>
1 在pom.xml引入
版本环境需保持一致
<spring-boot.version>2.1.8.RELEASE</spring-boot.version>
<spring-cloud.version>Greenwich.SR3</spring-cloud.version>
2 开启注册服务发现@EnableDiscoveryClient
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableDiscoveryClient
public class GulimallGatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GulimallGatewayApplication.class, args);
    }
}
3 配置nacos注册中心地址applicaion.properties
spring.application.name=glmall-gateway
spring.cloud.nacos.discovery.server-addr=192.168.11.1:8848
server.port=88
4 bootstrap.properties 填写配置中心地址
spring.application.name=glmall-coupon
spring.cloud.nacos.config.server-addr=192.168.11.1:8848
spring.cloud.nacos.config.namespace=a791fa0e-cef8-47ee-8f07-5ac5a63ea061
5 nacos里创建命名空间gateway,然后在命名空间里创建文件glmall-gateway.yml
spring:
    application:
        name: glmall-gateway
6 在项目里创建application.yml
spring:
  cloud:
    gateway:
      routes:
        - id: baidu_route
          uri: http://www.baidu.com
          predicates:
            - Query=url,baidu

- id: test_route
          uri: http://www.qq.com
          predicates:
            - Query=url,qq
测试 localhost:8080?url=baidu # 跳到百度页面
测试 localhost:8080?url=baidu # 跳到qq页面

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK