1、创建eureka-server注册中心工程,配置跟之前讲eureka文章中一样,这里不再赘述
1.1、端口8888
2、创建一个demo-client工程
2.1、demo-client启动类跟之前一样,其配置文件也一样,没有做太多配置,这里不再赘述,端口:7070,服务名:client-a。
2.2、编写一个测试接口:
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @GetMapping("/add") public Integer add(Integer a, Integer b) { return a + b; } }
3、创建一个zuul-gateway工程
3.1、pom配置:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> </parent>
<!-- 管理依赖 --> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <!-- springboot web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId> </dependency> <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>
3.2、工程启动类:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @SpringBootApplication @EnableDiscoveryClient @EnableZuulProxy public class ZuulServerApplication { public static void main(String[] args) { SpringApplication.run(ZuulServerApplication.class, args); } }
3.3、配置文件:
spring:
application:
name: zuul-gateway
server:
port: 5555 #指定网关服务端口
eureka:
client:
serviceUrl:
defaultZone: http://${eureka.host:127.0.0.1}:${eureka.port:8888}/eureka/ #指定注册中心
instance:
prefer-ip-address: true
# 将所有/client开头的URL映射到client-a这个服务中
zuul:
routes:
client-a:
path: /client/**
serviceId: client-a
3、启动三个工程:eureka-server、zuul-gateway、demo-client
1、直接访问服务接口:localhost:7070/add?a=100&b=1
2、通过zuul网关访问接口:localhost:5555/client/add?a=100&b=100
可以看到通过网关也能正常访问到demo-client服务中的接口,这是因为在网关项目配置文件中,指定了路由规则,当浏览器向网关发送请求的时候,它会去注册中心拉取服务列表,如果发现有指定的映射规则,就会按照我们配置的规则路由到对应的服务接口上。