个人记录裸辞后崛起复习之one day(入门级)--gateway实战+源码解读

157 阅读2分钟

nginx和gateway区别:nginx为第三方或者用户使用,gateway为微服务之间使用。

  • Route: 路由是⽹关的基本组成部分,它是由id、⽬标uri、断⾔组成,如果断⾔为true,则匹配该路由,转向到当前路由的URI。
  • Predicate:断⾔,⽤户请求的匹配规则(正则表达式路径/url带请求参数/header带请求参数)。
  • Filter:过滤器,⽤于对请求进行前置、后置处理。
  1. 实现GatewayFilter-bean注入RouteLocator绑定自定义过滤器;

  2. 继承gateway内置过滤器AbstractNameValueGatewayFilterFactory-yaml配置;

  3. 实现GlobalFilter内置的全局过滤器默认⽣效,⽆需开发者⼲预,会拦截过滤所有到达网关服务器的请求; @Component public class AuthenticationFilter implements GlobalFilter {

    @Autowired private TokenService tokenService; // 假设有一个TokenService来验证JWT令牌

    @Override public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { String token = exchange.getRequest().getHeaders().getFirst("Authorization"); //拦截请求获取JWT if (token == null || !tokenService.validateToken(token)) { ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.UNAUTHORIZED); DataBuffer buffer = response.bufferFactory().wrap("Unauthorized".getBytes(StandardCharsets.UTF_8)); return response.writeWith(Mono.just(buffer)); } return chain.filter(exchange); } }

@Service public class TokenService {

@Value("${jwt.secret}")
private String secretKey;

public boolean validateToken(String token) {
    // 这里只是一个示例实现
    try {
        Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
        // 进一步的验证逻辑:检查令牌的过期时间等
        return true;
    } catch (Exception e) {
        return false;
    }
}

}


http://localhost:9999/order/query--->http://localhost:8002/order/query http://localhost:9999/product/query--->http://localhost:8001/product/quer server: port: 9999 spring: application: name: gateway-server cloud: gateway: routes: # 配置api-service1路由规则 - id: api-service1 uri: 'http://localhost:8001' //路由是由id、⽬标uri、断⾔组成,用户请求匹配断言,转向到当前路由的URI predicates: //⽤户请求的匹配规则 - Path=/product/** # 配置api-service2路由规则 - id: api-service2 uri: 'http://localhost:8002' predicates: - Path=/order/**

网关限流:yaml配置,常见算法计数器/令牌桶/漏桶 filters: - name: RequestRateLimiter args: redis-rate-limiter.replenishRate: 1 #令牌桶每s的填充速度 redis-rate-limiter.burstCapacity: 2 #令牌桶容量 redis-rate-limiter.requestedTokens: 1 #每个请求消耗多少个令牌 key-resolver: '#{@keyResolver}' #令牌桶key生成

example.com/api/users/1…

server { listen 80; server_name example.com;

location /api/ {
    proxy_pass http://api-gateway/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

}

spring: cloud: gateway: routes: - id: user-service uri: http://internal-api/users predicates: - Path=/api/users/** filters: - RewritePath=/api/(?.*), /${segment}

--------------------------------------------nginx+gateway+nacos---------------------------------- server: port: 8080

spring: application: name: my-service cloud: nacos: discovery: server-addr: 127.0.0.1:8848 ---------------普通springboot-----------------

spring: application: name: gateway cloud: gateway: routes: - id: my-service-route uri: lb://my-service predicates: - Path=/my-service/** filters: - StripPrefix=1 nacos: discovery: server-addr: 127.0.0.1:8848 ---------------gateway服务-----------------

http { upstream gateway_cluster { server localhost:8081 weight=3; server localhost:8082 weight=1; }

server {
    listen 80;

    location / {
        proxy_pass http://gateway_cluster;
    }
}

} ---------------nginx服务----负载均衡策略==轮询/最少连接/权重/hash-------------

gateway+jwt案例:jwt获取用户信息,app和web端分别实现通过jwt获取用户信息的handler; LoginAuthFilter根据情况调用app或web端的handler获取用户信息,LoginAuthFilter继承gateway内置过滤器; 将LoginAuthFilter配置到gateway服务yml; spring.cloud.gateway.routes[1].id=asset-service spring.cloud.gateway.routes[1].uri=lb://asset-service spring.cloud.gateway.routes[1].predicates[0]=Path=/asset-service/** spring.cloud.gateway.routes[1].filters[0]=StripPrefix=1 spring.cloud.gateway.routes[1].filters[1]=LoginAuthFilter

@EnableDiscoveryClient 作用:使得应用成为服务发现客户端,允许应用注册到服务注册中心(如Eureka、Consul、Nacos等),并发现其他服务。