SpringCloudAPI网关服务Zuul

SpringCloud微服务就是把一个大的项目拆分成多个小的模块,然后模块之间通过远程调用、服务治理的技术互相配合工作,随着业务的增加,项目也将会越来越庞大,接口数量也随之增加,对外提供服务的接口也会增加,运维人员对于这些接口的管理也会变得越来越难。另一方面对于一个系统来说,权限管理也是一个不可少的模块,在微服务架构中,系统被拆分,不可能每个模块都去添加一个个权限管理,这样系统代码重复、工作量大、后期维护也难。为了解决这些常见的架构问题,API网关应运而生。SpringCloudZuul是基于Netflix Zuul实现的API网关组件,它实现了请求路由、负载均衡、校验过滤、与服务治理框架的结合、请求转发是的熔断机制和服务的聚合等功能。

 

 

 相当于小区保安,要想进小区需经过保安

也相当于饺子皮,包装了饺子馅让人看不到饺子里面有什么东西

新建一个SpringBoot项目,这里命名api-gateway,然后导入相关依赖:

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

在主类上使用@EnableZuulProxy注解开启API网关服务功能

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

在配置文件中添加路由的规则配置

spring:
  application:
    name: api-gateway
server:
  port: 8500
zuul:
  routes:
    # 面向服务的路由
    api-a:
      path: /api-a/**
      serviceId: FEIGN-CONSUMER
    # 传统的路由
    api-b-url:
      path: /api-b-url/**
      url: http://localhost:30000/
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8888/eureka/

这里的代码是接着前面的,启动eureka-server、user-server、feign-consumer、article-server和api-gateway。我没添加了eureka的依赖,所以api-gateway也是服务提供方在注册中心注册:

然后访问http://localhost:8500/api-a/feign_consumer/findhttp://localhost:8500/api-b-url/a/u/1

 在上面的配置文件文件中,使用两种路由规则的配置方法,一种是面向服务的,一种是使用传统的url。所有符合/api-a/**的请求都将转发到feign-consumer,同样所有符合/api-b-url/**的请求都将转发到http://localhost:30000/,也就是前面使用的article-service。两种规则的配置很明显:面向服务的使用serviceId配置服务实例,而传统的直接使用服务的地址。

猜你喜欢

转载自blog.csdn.net/qq_34971162/article/details/81389520