在Spring Cloud中,服务网关通常使用Zuul来实现。以下是一个使用Zuul作为服务网关的简单示例:
- 添加依赖到你的
pom.xml:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>- 配置你的
application.properties或application.yml以启用Zuul:
spring.application.name=api-gateway
server.port=80
zuul.routes.my-service.path=/my-service/**
zuul.routes.my-service.serviceId=my-service- 创建一个Spring Boot应用并使用
@EnableZuulProxy注解启用Zuul代理功能:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@EnableZuulProxy
@SpringBootApplication
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
}在这个例子中,服务网关会代理所有到/my-service/**的请求到名为my-service的服务。这个服务应该在Spring Cloud服务发现机制下注册,例如Eureka。这样配置后,访问http://localhost/my-service/...的请求会被转发到对应的服务。