Gateway HelloWorld快速入门
我们搞两个服务,分别是product产品服务项目,以及order订单服务项目,我们搞个小案例,搞一个网关,统一对path请求地址进行管理;
一: gateway-server 配置
gateway依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency>
application.yml配置:
server: port: 80 servlet: context-path: / spring: application: name: gateway-server cloud: gateway: routes: # 路由规则定义 - id: product-service # 路由ID uri: http://localhost:8080/ # 路由地址 predicates: # 断言规则 - Path=/product/** - id: order-service # 路由ID uri: http://localhost:8081/ # 路由地址 predicates: # 断言规则 - Path=/order/**
启动类:
@SpringBootApplication public class GatewayServerApplication { public static void main(String[] args) { SpringApplication.run(GatewayServerApplication.class, args); } }
二: product-demo 服务
application.yml
server: port: 8080 servlet: context-path: / spring: application: name: product-demo
测试接口:
@RestController @RequestMapping("/product") public class ProductController { @GetMapping("/{id}") public Product detail(@PathVariable("id")Integer id){ return new Product(id,"xxx商品"+id,2,100.00); } }
三: order-demo 服务
application.yml配置:
server: port: 8081 servlet: context-path: / spring: application: name: order-demo
测试接口:
@RestController @RequestMapping("/order") public class OrderController { @GetMapping("/{id}") public Order detail(@PathVariable("id")Integer id){ return new Order(id,"354324324",232.11,"用户信息"+id,"商品信息"+id); } }
最终测试:
http://localhost:8001/order/2 和 http://localhost/order/2 一样的测试结果 ; 其他的类似