一、网关相关配置

1、在pom.xml引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>infrastructure</artifactId>
        <groupId>com.javaclimb</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>api_gateway</artifactId>
    <dependencies>
        <!-- 网关 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <!--服务注册-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <dependency>
            <groupId>com.javaclimb</groupId>
            <artifactId>common_util</artifactId>
            <version>0.0.1-SNAPSHOT</version>
            <!-- 排除 spring-boot-starter-web, 否则和 gateway 中的 webflux 冲突  -->
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-web</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!--将随着spring-boot-starter-web排除的servlet-api添加回来 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

        <!--gson-->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

2、application.yml

server:
  port: 8090

spring:
  profiles:
    active: dev
  application:
    name: infrastructure-apigateway

  cloud:
    # nacos 服务
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    gateway:
      discovery:
        locator:
          # gateway 可以发现 nacos 中的微服务
          enabled: true
      routes:
        - id: service-edu # 随便起
          # uri: http://localhost:9110 # 目标路由
          # 目标路由,必须和 nacos 中微服务名称一样, lb -> 以负载均衡的方式访问
          uri: lb://service-edu
          predicates:
            # 路径断言,只要这个条件成立,就转发到上面的地址
            - Path=/user/**, /*/edu/**
        - id: service-cms
          uri: lb://service-cms
          predicates:
            - Path=/*/cms/**
          # 过滤器
          filters:
            - SetStatus=250 # 修改响应状态码为 250
        - id: service-oss
          uri: lb://service-oss
          predicates:
            - Path=/*/oss/**
        - id: service-trade
          uri: lb://service-trade
          predicates:
            - Path=/*/trade/**
        - id: service-ucenter
          uri: lb://service-ucenter
          predicates:
            - Path=/*/ucenter/**
        - id: service-vod
          uri: lb://service-vod
          predicates:
            - Path=/*/vod/**
        - id: service-statistics
          uri: lb://service-statistics
          predicates:
            - Path=/*/statistics/**
        - id: service-acl
          uri: lb://service-acl
          predicates:
            - Path=/*/acl/**

3、编写启动类

package com.stu.infrastructure;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/******************************
 * 用途说明:
 * 作者姓名: Administrator
 * 创建时间: 2022-07-27 22:56
 ******************************/

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableDiscoveryClient
public class ApiGatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class, args);
    }
}

4、网关解决跨域问题

package com.stu.infrastructure.confing;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.util.pattern.PathPatternParser;

/******************************
 * 用途说明:
 * 作者姓名: Administrator
 * 创建时间: 2022-07-27 23:16
 ******************************/
@Configuration
public class CorsConfig {
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        // #允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin
        config.addAllowedOrigin("*");
        // #允许访问的头信息,*表示全部
        config.addAllowedHeader("*");
        // 允许提交请求的方法类型,*表示全部允许
        config.addAllowedMethod("*");

        org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource source =
                new org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }

}

5、全局Filter,统一处理会员登录与外部不允许访问的服务

package com.stu.infrastructure.filter;

/******************************
 * 用途说明:
 * 作者姓名: Administrator
 * 创建时间: 2022-07-27 23:35
 ******************************/

import com.stu.service.base.utils.JwtUtils;
import com.google.gson.JsonObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();

        // 匹配路由
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        // 判断路径中如果含有 /api/**/auth/**,则需要鉴权
        if (antPathMatcher.match("/api/**/auth/**", path)) {
            // 获取 token
            List<String> tokenList = request.getHeaders().get("token");
            // 没有 token
            if (tokenList == null) {
                ServerHttpResponse response = exchange.getResponse();
                // 鉴权失败
                return this.out(response);
            }

            // token 检验失败
            boolean isCheck = JwtUtils.checkJwtToken(tokenList.get(0));
            if (!isCheck) {
                ServerHttpResponse response = exchange.getResponse();
                // 鉴权失败
                return this.out(response);
            }
        }
        // 放行: 使用过滤器链,将请求继续向下传递
        return chain.filter(exchange);
    }


    /**
     * 定义当前过滤器的优先级
     *  - 值越小, 优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 使用 webflux 输入请求信息
     */
    private Mono<Void> out(ServerHttpResponse response) {

        JsonObject message = new JsonObject();
        message.addProperty("success", false);
        message.addProperty("code", 28004);
        message.addProperty("data", "");
        message.addProperty("message", "鉴权失败");
        byte[] bytes = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        //指定编码,否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        //输出http响应
        return response.writeWith(Mono.just(buffer));
    }

}

六、前端俩项目修改连接地址

把前端请求地址的端口修改位网关的接口

 

原文地址:http://www.cnblogs.com/konglxblog/p/16800765.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性