spring cloud gateway入门案例(先跑起来)

目的:我们的目的是从初学者的角度,用gateway跑helloworld

1.创建springboot工程

首先利用idea 创建springboot工程。我是先创建了一个gate-parent工程,然后删掉了src作为父工程,然后创建了一个gate-way和web的子模块。
gate-way:网关工程
web:普通的web工程
在这里插入图片描述

2.gate-way工程引入依赖

引入网关的依赖

  <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-gateway</artifactId>
  </dependency>
3.完善网关工程

配置网关工程的配置,与web工程进行关联。

spring:
  cloud:
    gateway:
      routes:
        - id: after_route     #一个路由(服务)的唯一标识
          uri: http://localhost:9999    #服务的地址
          predicates:   #过滤条件
            - Cookie=mycookie,mycookievalue   #必须cookie中携带mycookie=mycookievalue
server:
  port: 8888
4.编写web controller
package com.example.web.action;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class HelloController {
    @GetMapping("/hello/{name}")
    public String hello(@PathVariable String name) {
        return "hello " + name;
    }
}

在这里插入图片描述

5.启动服务

通过application分别启动gate-way(8888端口)和web(9999端口)工程。

6.访问web工程

直接访问web工程: http://localhost:9999/hello/w
在这里插入图片描述

7. 通过网关工程访问

http://localhost:8888/hello/w
在这里插入图片描述

8.设置cookie之后网关访问

添加cookie之后,可以通过网关访问web工程
在这里插入图片描述

9.总结

到这里,我们的最简单的工程案例就完了,相信对于刚接触spring cloud gate-way的小伙伴应该还是很有帮助的。麻雀虽小五脏俱全。
其实就是利用一个工程对外放开服务,其他的服务都通过该服务进行跳转。
对于http://localhost:8888/hello/w 携带mycookie=mycookievalue 的cookie之后,转发到http://localhost:9999/hello/w。

spring:
  cloud:
    gateway:
      routes:
        - id: after_route     #一个路由(服务)的唯一标识
          uri: http://localhost:9999    #服务的地址
          predicates:   #过滤条件
            - Cookie=mycookie,mycookievalue   #必须cookie中携带mycookie=mycookievalue
server:
  port: 8888
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值