从零开始玩转SpringCloud(二):Gateway网关对接注册中心

从零开始玩转SpringCloud(二):Gateway网关对接注册中心

简介:Spring Cloud Gateway旨在为微服务架构提供一种简单而有效的统一的API路由管理方式。

项目搭建

  1. 引入依赖
<!--Eureka 客户端-->
<dependency>
	<groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--Gateway 路由-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

注意:不要引入spring-boot-starter-web包,会导致Gateway启动抛出异常,错误如下。因为Spring Cloud Gateway 是使用 netty+webflux实现,webflux与web是冲突的。

Consider defining a bean of type 'org.springframework.http.codec.ServerCodecConfigurer' in your configuration.
  1. 在Application中使用@EnableEurekaClient
package com.example.gateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

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

  1. 配置自动将注册中心的服务映射为路由
server:
  port: 8081

spring:
  application:
    name: gateway
  cloud:
    gateway:
      # 此处配置表示开启自动映射Eureka下发的路由
      discovery:
        locator:
          enabled: true
          lowerCaseServiceId: true

eureka:
  client:
    # Eureka Server地址
    service-url:
      defaultZone: http://localhost:8760/eureka/
  1. 至此,已经可以直接通过gateway访问其他注册在Eureka中的服务的接口了。如客户端接口地址:http://localhost:8080/test,注册名称为client,则访问地址为http://localhost:8081/client/test。

猜你喜欢

转载自blog.csdn.net/weiwoyonzhe/article/details/88653101
今日推荐