1.新建一个springboot项目--gateway
maven依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.demo</groupId>
<artifactId>gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>gateway</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<!-- 管理依赖 -->
<dependencyManagement>
<!-- 管理springcloud依赖 -->
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 引入zuul依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<!--引入eureka客户端依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml配置
#服务启动端口号
server:
port: 8088
#eureka配置
eureka:
# 心跳检测检测与续约时间
# 测试时将值设置设置小些,保证服务关闭后注册中心能及时踢出服务
instance:
###Eureka客户端向服务端发送心跳的时间间隔,单位为秒(客户端告诉服务端自己会按照该规则)
lease-renewal-interval-in-seconds: 1
####Eureka服务端在收到最后一次心跳之后等待的时间上限,单位为秒,超过则剔除(客户端告诉服务端按照此规则等待自己)
lease-expiration-duration-in-seconds: 2 #生产环境下一般默认90s
client:
#是否需要从注册中心获取信息
fetch-registry: true
#需要注册服务到服务中心
register-with-eureka: true
service-url:
defaultZone: http://62.234.109.11:8100/eureka
#spring相关配置
spring:
application:
#服务名字(注册到注册中心)
name: gateway
### 配置网关反向代理
zuul:
routes:
producer:
### 以 /producer/访问转发到生产者服务(默认实现负载均衡)
path: /producer/**
serviceId: producer
启动类添加@EnableEurekaClient @EnableZuulProxy
2.新建一个eurekaserver和生产者producer项目:
注册中心:
这里有网关项目,和两个生产者的项目。 网关项目和生产者项目要么都在服务器上,要么都在本地,不能一个在服务器,一个在本地。
3.访问网关项目地址,反向代理到生产者项目
访问: localhost:8088/producer/getinfo
producer为网关配置路径 getinfo为生产者项目的一个方法
实现反向代理和负载均衡