gateway网关小demo

zuul1.x系列作为网关,基于servlet实现,属于多线程同步阻塞模型;zuul2.x改写netty,属于异步非阻塞模型;gateway属于异步非阻塞模型。

这里基于spring-session+redis+zuul session共享示例,将其中的zuul网关替换为gateway网关技术。

工程改造

pom依赖

引入gateway依赖包

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
	        <groupId>org.springframework.boot</groupId>
	        <artifactId>spring-boot-starter-actuator</artifactId>
	    </dependency>

增加eureka注册中心依赖信息,这里不能使用spring-cloud-starter-netflix-eureka-server,与gateway的jar包有冲突,可以参考Consider defining a bean of type ‘org.springframework.http.codec.ServerCodecConfigurer‘ in your conf

	    <dependency>
		    <groupId>org.springframework.cloud</groupId>
		    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
		</dependency>

代码启动类

注解该类为一个springboot工程,并且通过@EnableDiscoveryClient将其注册到注册中心

@EnableDiscoveryClient
@SpringBootApplication
public class Gateway {

	public static void main(String[] args) {
		SpringApplication.run(Gateway.class, args);
	}
	
}

配置文件

server:
  port: 5000  #gateway网关服务端口号
spring:
  application:
    name: gateway  #gateway网关实例名称
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true       #将请求路由至DiscoveryClient发现的注册中心的服务
          lowerCaseServiceId: true #请求url是否大小写敏感,默认false敏感;true表示不敏感
      routes:  #路由信息配置
      - id: um_route #一个id为一组路由信息
        uri: lb://um  #将请求路由到um服务
        predicates:   #请求格式
        - Path=/um/**
      - id: bm_route
        uri: lb://bm
        predicates:
        - Path=/bm/**
management:
  endpoints:
    web:
      exposure:
        include: '*' #暴露所有端点信息给actuator
eureka:             # eureka服务注册中心信息
  instance:
    prefer-ip-address: true 
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
          

上面配置文件中uri部分内容未 lb://bm ,lb 表示load balance(负载均衡),将请求分发给所有以bm命名的工程。

项目测试

依次启动 servicecenter、gateway、UserManagerA、UserManagerB 和 BuyManager工程,启动完毕后,打开注册中心 http://localhost:8761/ 可以看到各实例注册成功

功能测试易正常。

gateway网关测试还有另一种方式,在gateway的actuator浏览器信息查看 http://localhost:5000/actuator/gateway/routes 

这里,说明gateway负责分发两个路由配置信息。

至此,一个简单的gateway小demo完成。

猜你喜欢

转载自blog.csdn.net/magi1201/article/details/112683340