一、网关相关配置
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)); } }
六、前端俩项目修改连接地址
把前端请求地址的端口修改位网关的接口
标签:网关,lb,service,springframework,API,org,import,com From: https://www.cnblogs.com/konglxblog/p/16800765.html