SpringCloud搭建微服务之Zuul网关
以下是一个使用Spring Cloud构建Zuul网关的简单示例:
- 在
pom.xml
中添加依赖:
<dependencies>
<!-- Spring Cloud Netflix Zuul -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<!-- Spring Cloud Eureka Client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
- 配置
application.yml
:
spring:
application:
name: api-gateway
server:
port: 8080
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
zuul:
routes:
user-service:
path: /user-service/**
serviceId: user-service
order-service:
path: /order-service/**
serviceId: order-service
- 启动类添加
@EnableZuulProxy
注解:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@SpringBootApplication
@EnableZuulProxy
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
}
以上代码配置了一个简单的Zuul网关,它将请求路由到服务ID为user-service
和order-service
的微服务。当客户端向http://localhost:8080/user-service/...
或 http://localhost:8080/order-service/...
发送请求时,网关会将请求转发到相应的微服务。
确保您的Eureka服务注册中心运行在http://localhost:8761
,并且user-service
和order-service
已注册服务。这样,网关就可以根据配置将流量路由到正确
评论已关闭