spring cloud:gateway-eureka

gateway-server-eureka

1. File-->new spring starter project

2.add dependency

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

3.Edit application.yml

server:
  port: 8080
spring:
  application:
    name: gateway-server-eureka
  cloud:
    gateway:
#      routes:
#      - id: neo_route
#        uri: https://www.cnblogs.com/alittlesmile/
#        predicates:
#        - Path=/alittlesmile
      discovery:
        locator:
          enabled: true

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8000/eureka/

配置说明:

  • spring.cloud.gateway.discovery.locator.enabled:是否与服务注册于发现组件进行结合,通过 serviceId 转发到具体的服务实例。默认为 false,设为 true 便开启通过服务中心的自动根据 serviceId 创建路由的功能。
  • eureka.client.service-url.defaultZone指定注册中心的地址,以便使用服务发现功能

修改完成后启动 gateway-server-eureka 项目,访问注册中心地址 http://localhost:8000/ 即可看到名为 GATEWAY-SERVER-EUREKA的服务。

4.program

package com.smile;

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

@SpringBootApplication
@EnableEurekaClient
public class GatewayServerEurekaApplication {

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

}

5.Run

开启之后我们就可以通过地址去访问服务了,格式如下:

http://网关地址/服务名称(大写)/**

http://localhost:8084/FSH-HOUSE/house/1

这个大写的名称还是有很大的影响,如果我们从Zull升级到Spring Cloud Gateway的话意味着请求地址有改变,或者重新配置每个服务的路由地址,通过源码我发现可以做到兼容处理,再增加一个配置即可:

spring.cloud.gateway.discovery.locator.lowerCaseServiceId=true

配置完成之后我们就可以通过小写的服务名称进行访问了,如下:

http://网关地址/服务名称(小写)/**

http://localhost:8084/fsh-house/house/1

启动producer,producer-1

在浏览器多次访问地址:http://localhost:8080/PRODUCER/getHello?name=xx,页面交替返回以下信息:

hello xx
hello xx,this is producer 1

说明后端服务自动进行了均衡负载。

原文地址:https://www.cnblogs.com/alittlesmile/p/10912252.html