美文网首页
搭建一套完整的微服务之网关路由-Zuul

搭建一套完整的微服务之网关路由-Zuul

作者: bearPotMan | 来源:发表于2018-08-24 00:30 被阅读0次

本文就来说一下怎么去配置网关路由?

1. 创建项目gateway

使用Spring Initializr来快速构建网关项目,注意选择下面的组件


2. 基础配置

(1). 首先需要在启动类添加注解@EnableZuulProxy

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

(2). 修改配置文件application.yml

spring:
  application:
    name: gateway
server:
  port: 8080
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

3. 检查是否已经注册到eureka


ok,已经成功注册到eureka。

4. 真正的网关路由

(1). user-service项目添加一个接口用来测试

@RestController
public class LoginController {
    @GetMapping("/login")
    public String login(){
        return "hello,bearPotMan";
    }
}

重启user-service,测试接口是否可用
访问http://localhost:8081/login


ok,没问题!

(2). 修改gateway项目启动类

@SpringBootApplication
@EnableZuulProxy // 添加注解,启动路由代理
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}

重启gateway项目,访问http://localhost:8080/user-service/login
注意: 默认路由规则 = 域名 + 端口 + 对应服务名(spring.application.name) + 接口地址


ok,可以正常显示。
如果想要自定义路由规则,就需要在网关的配置文件中添加配置,比如
spring:
  application:
    name: gateway
server:
  port: 8080
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
zuul:
  routes:
    # 自定义规则名
    user-service-api:
      # url地址
      path: /user-api/**
      # 要路由到哪个服务 -- 对应于具体服务的 spring.application.name
      serviceId: user-service

ok,重启网关服务,访问http://localhost:8080/user-api/login


可以正常显示,完美!
ok,以上就是本次分享的内容关于如何实现服务注册与发现服务端
下一篇就来说一下配置中心 Config 的基础配置。

我是bearPotMan,一个经验不足的十八线演(码)员(农)。
Know everything,control everything!

相关文章

网友评论

      本文标题:搭建一套完整的微服务之网关路由-Zuul

      本文链接:https://www.haomeiwen.com/subject/amtpiftx.html