前面已经简单介绍了搭建Eureka注册中心,Feign消费,Service提供者,那么外部调用的时候是直接走Feign来调用服务么?其实不然,后端接口并不会直接开方,而是通过一个统一网关服务,来映射请求的api,路由到相对应的服务.
沿用之前的服务来完成Zuul的测试.
一 : 新建一个boot工程命名为cloud-shop-gateway
二 : 在pom中添加依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
三 : 在Application启动类添加注解开启zuul服务
package cn.sh.daniel;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@SpringBootApplication
@EnableZuulProxy //添加注解支持网关路由
public class CloudShopGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(CloudShopGatewayApplication.class, args);
}
}
四 : 配置properties.yml
server:
port: 6001
spring:
application:
name: cloud-shop-gateway
eureka:
client:
service-url:
defaultZone: http://daniel-cloud-shop-eureka:eureka123123@server1:9001/eureka/,http://daniel-cloud-shop-eureka:eureka123123@server2:9002/eureka/
zuul:
routes:
api-user.path: /shop/user/**
api-user.serviceId: cloud-shop-feign
api-user.path: /shop/user/** 指定对外映射的地址
api-user.serviceId: cloud-shop-feign 指定注册到注册中心的服务的 serviceId
五 : 启动网关服务,测试
之前测试Feign的测试地址为: http://localhost:7001/user/findUser?name=cloud&password=001010
现在调用网关的地址为: http://localhost:6001/cloud-shop-feign/user/findUser?name=cloud&password=001010
可以看出和我们配置的映射关系