彤医通项目之springCloud Gateway网关 初体验

网关

客户端多次请求不同的微服务,存在跨域问题,认证问题,重构问题。

之前

使用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组件。

  1. 使用后不需要在Controller上加@OriginCross注解。
  2. 做限流、安全、权限控制。

将Gateway网关在nacos中进行注册
将微服务模块在nacos中进行注册

Gateway使用

  1. 搭建模块
  2. 引入依赖,编写配置
		<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>
  1. 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/**
  1. 配置启动类
/**
 * 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地址不同、端口号不同

  1. 跨域解决:使用网关方式,可以不写注解。而在网关微服务中添加配置类。
/**
 * 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);
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值