Spring Cloud服务网关

本文介绍了Spring Cloud服务网关的主要特性,包括认证、安全、动态路由等,并详细讲解了如何基于RestTemplate自定义服务网关,以及Spring Cloud Netflix Zuul和Spring Cloud Gateway的基本使用、配置和核心API。通过实例展示了服务网关的功能和实现方式。

版本信息

Spring Cloud : Hoxton.SR1

Spring Boot : 2.2.2.RELEASE

Zookeeper : 3.5.6 (注册中心使用)

服务网关特性

服务网关是干什么用的?

  • 认证
  • 安全(授权)
  • 动态路由

基于RestTemplate自定义服务网关

服务端演示提供服务
1.添加pom依赖

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

<!--zookeeper 客户端-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
</dependency>

2.服务网关服务应用GatewayServerApplication

/**
 * 服务网关服务应用
 *
 * @author FelixFly <chenglinxu@yeah.net>
 * @date 2020/2/8
 */
@SpringBootApplication
public class GatewayServerApplication {
   
   

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

3.演示服务端点

/**
 * 演示服务端点
 *
 * @author FelixFly <chenglinxu@yeah.net>
 * @date 2020/2/8
 */
@RestController
public class EchoController {
   
   

    @Autowired
    private Environment environment;


    @GetMapping("/echo")
    public String echo(String message) {
   
   
        // 由于采用的是随机端口,这地方必须采用这个方式获取端口
        String port = environment.getProperty("local.server.port");
        return "ECHO(" + port + "):" + message;
    }
}

4.服务配置application.yml

spring:
  application:
    name: gateway-server
  cloud:
    zookeeper:
      connect-string: 127.0.0.1:2181
server:
  port: 0

启动服务,根据启动日志查看本地的随机端口,此次端口是54692

http://127.0.0.1:54692/echo?message=Hello 返回信息ECHO(54692):Hello

自定义服务网关

基于Servlet

配置文件application.yml

spring:
  application:
    name: gateway-zuul
  cloud:
    zookeeper:
      connect-string: 127.0.0.1:2181
server:
  port: 7070

基于DiscoveryClient
GatewayCustomServlet网关Servlet

包名:top.felixfly.cloud.gateway.custom

/**
 * 服务网关Servlet实现
 *
 * @author FelixFly <chenglinxu@yeah.net>
 * @date 2020/2/8
 */
@WebServlet(name = "gateway", urlPatterns = "/gateway/*")
public class GatewayCustomServlet extends HttpServlet {
   
   

    @Autowired
    private DiscoveryClient discoveryClient;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   
   
        // 访问地址的Uri:/{service-name}/${service-uri}
        String pathInfo = req.getPathInfo();
        String[] paths = StringUtils.split(pathInfo.substring(1), "/");
        // 服务名称
        String serverName = paths[0];
        // 服务访问地址
        String serverURI = paths[1];
        // 获取服务实例
        ServiceInstance serviceInstance = choose(serverName);
        // 目标地址
        String targetURL = createTargetURL(serviceInstance, serverURI, req);
        RestTemplate restTemplate = new RestTemplate();
        String method = req.getMethod(
### Spring Cloud 服务网关实现配置 #### 网关概述 Spring Cloud GatewaySpring Cloud 生态系统中的新一代 API 网关工具,旨在替代 Netflix Zuul[^1]。它基于 Spring Framework 和 Project Reactor 构建,支持高吞吐量和低延迟的特性。 #### 配置文件调整 在 `application.yml` 文件中,如果不再需要手动指定路由规则,则可以移除 `spring.cloud.gateway.routes` 及其子节点的相关配置[^2]。这通常用于动态加载路由或者通过其他方式管理路由表的情况。 #### 核心功能解析 本文提到 Spring Cloud Gateway 的核心概念及其快速部署方法,并强调了过滤器(Filters)的重要性和具体应用[^3]。以下是几个关键点: - **路由机制** 所有外部请求均需经过网关,随后依据预设规则将这些请求转发至对应的服务实例。这一过程即为路由操作[^4]。 - **负载均衡** 当目标服务存在多个副本时,网关会自动执行负载均衡策略来分配流量,从而提高系统的可用性和性能。 - **过滤器的作用** 过滤器分为两大类:全局过滤器和局部过滤器。它们可以在请求到达后端服务之前或响应返回客户端之后施加特定逻辑。例如,可以通过自定义过滤器解决跨域资源共享 (CORS) 问题。 #### 自定义过滤器示例 以下是一个简单的自定义全局过滤器代码片段,展示如何记录每次请求的时间戳: ```java import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; @Component public class LoggingGlobalFilter implements GlobalFilter { @Override public Mono<Void> filter(org.springframework.web.server.ServerWebExchange exchange, GatewayFilterChain chain) { System.out.println("Request received at: " + new java.util.Date()); return chain.filter(exchange); } } ``` 此代码实现了 `GlobalFilter` 接口并重写了 `filter()` 方法,在其中打印当前时间戳以便调试用途。 --- #### 总结 综上所述,Spring Cloud Gateway 提供了一种强大而灵活的方式来管理和控制进入微服务体系的 HTTP 流量。无论是静态还是动态路由设置、内置还是定制化过滤器开发,都可以满足不同场景下的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值