1、在parent父工程中創建一個空的Maven項目infrastructure
同樣刪除src全部
2、在infrastructure模塊下創建api_gateway模塊
注意:路徑不能搞錯了
注意:修改pom.xml文件
修改後pom.xml
3、編寫application.properties配置文件
# 服務端口
server.port=9999
# 服務名
spring.application.name=service-gateway
# nacos服務地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
#Gateway 網關配置
#使用服務發現路由
spring.cloud.gateway.discovery.locator.enabled=true
#設置路由id (建議服務的名稱)
spring.cloud.gateway.routes[0].id=service-file
#設置路由的uri (nacos註冊服務名稱)
spring.cloud.gateway.routes[0].uri=lb://service-file
#設置路由斷言
spring.cloud.gateway.routes[0].predicates= Path=/fileservice/**
#配置service-user服務
spring.cloud.gateway.routes[1].id=service-user
spring.cloud.gateway.routes[1].uri=lb://service-user
spring.cloud.gateway.routes[1].predicates= Path=/eduservice/**
4、編寫啓動類
在java目錄下,先創建包com.itydf.gateway
ApiGatewayApplication.java啓動類
@SpringBootApplication
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
}
網關相關配置
1、網關解決跨域問題
com.itydf.gateway包下面創建config包,再在下面創建CorsConfig跨越配置類
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.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;
@Configuration
public class CorsConfig {
@Bean
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}
啓動測試
先啓動api_gateway,控制檯打印輸出,啓動網關模塊服務成功
再啓動另外兩個service_file和service_user模塊服務,另外查看Nacos我們的三個服務都被註冊進來了
隨便測試一個服務的功能接口
以service_user的查詢全部用戶信息接口爲列子:
瀏覽器輸入接口地址:http://localhost:9901/eduservice/crm-user/list,能正常訪問到。
注意:此時我們把9901端口改爲我們配置的網關服務統一接口
瀏覽器輸入接口地址:http://localhost:9999/eduservice/crm-user/list,也能正常訪問到。
查看api_gateway服務控制檯輸出,有這樣一段日誌輸出:
是不是成功了,這樣就成功解決了我們的跨越問題,解決了上一篇我們拋出的問題。