网关
客户端多次请求不同的微服务,存在跨域问题,认证问题,重构问题。
之前
使用nginx网关。
多台微服务,每台不同的端口,8081和8082。
请求 -> nginx(根据不同的请求地址端口Location)进行端口转发。
server{
listen 9001;
server_name localhost;
location ~ /hosp/{
proxy_pass http://localhost:8081;
}
location ~ /cmn/{
proxy_pass http://localhost:8082;
}
}
如今
SpringCloud Gateway组件。
- 使用后不需要在Controller上加@OriginCross注解。
- 做限流、安全、权限控制。
将Gateway网关在nacos中进行注册
将微服务模块在nacos中进行注册
Gateway使用
- 搭建模块
- 引入依赖,编写配置
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- 将gateway服务在nacos中注册 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
- application.properties
# 服务端口
server.port=9876
# 服务名
spring.application.name=service-gateway
# nacos服务地址,前提先启动nacos服务,必须配置nacos服务端口
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
#使用服务发现路由
spring.cloud.gateway.discovery.locator.enabled=true
#设置路由id
spring.cloud.gateway.routes[0].id=service-hosp
#设置路由的uri
spring.cloud.gateway.routes[0].uri=lb://service-hosp
#设置路由断言,代理servicerId为auth-service的/auth/路径
spring.cloud.gateway.routes[0].predicates= Path=/*/hosp/**
#设置路由id
spring.cloud.gateway.routes[1].id=service-cmn
#设置路由的uri
spring.cloud.gateway.routes[1].uri=lb://service-cmn
#设置路由断言,代理servicerId为auth-service的/auth/路径
spring.cloud.gateway.routes[1].predicates= Path=/*/cmn/**
- 配置启动类
/**
* gateway微服务模块 gateway网关代替nginx
* @Author Weton Li
* @Date 2021/4/30 14:00
*/
@SpringBootApplication
public class ServerGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ServerGatewayApplication.class,args);
}
}
Springcloud解决跨域
跨域原由:
访问协议不同http->https、IP地址不同、端口号不同
- 跨域解决:使用网关方式,可以不写注解。而在网关微服务中添加配置类。
/**
* gateway处理跨域,不再需要在Controller上使用CrossOrigin注解。
* @Author Weton Li
* @Date 2021/4/30 22:23
*/
@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);
}
}