SpringCloud版本:2021.0.1 SpringBoot版本:2.6.3
系列文章
SpringCloud学习(一)----- Eureka搭建
SpringCloud学习(二)----- SpringBoot Admin搭建(与Eureka整合)
SpringCloud学习(三)----- Gatewayw网关搭建
SpringCloud学习(四)----- Gatewayw网关完善(限流)
SpringCloud学习(五)----- Gatewayw网关完善(Resilience4j断路器)
SpringCloud学习(六)----- Gatewayw网关完善(防止SQL注入)
一、创建项目
1、打开IDEA,新建项目,和之前一样,打开Eureka项目后再新建一个Module项目。
2、前面的和之前新建的项目一样,不过选的依赖不一样了,要选SpringBoot admin 的client服务和Eureka的client服务以及最重要的Gateway 依赖。
3、然后又到加注解这一步了,在启动类上面加@EnableDiscoveryClient ,这是注册到Eureka服务的。
4、修改application.yml的配置,其中大部分配置和之前的差不多,就是新加了Gateway网关需要的配置而已。
其中的路由我写了个网址的转发 来进行测试,测试通过后就可以修改成自己的服务的地址了
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]': # 匹配所有请求
allowedOrigins: "*" #跨域处理 允许所有的域
allowedMethods: # 支持的方法
- GET
- POST
- PUT
- DELETE
discovery:
locator:
enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
routes:
#路径匹配
- id: find
uri: https://blog.csdn.net # 测试
predicates:
- Path=/csdn/**
下面是完整的配置
server:
port: 80
spring:
application:
name: test-gateway
security:
user:
name: test
password: 123456
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]': # 匹配所有请求
allowedOrigins: "*" #跨域处理 允许所有的域
allowedMethods: # 支持的方法
- GET
- POST
- PUT
- DELETE
discovery:
locator:
enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
routes:
#路径匹配
- id: find
uri: https://blog.csdn.net # 测试
predicates:
- Path=/csdn/**
# - id: test #id必须唯一,一般使用服务名
# uri: lb://test #lb://注册到Eureka里的服务名
# predicates:
# - Path=/test/**
# filters:
# - StripPrefix=1 #去掉Path前缀,参数为1代表去掉/test
eureka:
instance:
leaseRenewalIntervalInSeconds: 10
health-check-url-path: /actuator/health
hostname: 127.0.0.1
client:
registryFetchIntervalSeconds: 5
service-url:
defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@${eureka.instance.hostname}:8001/eureka/
management:
endpoints:
web:
exposure:
include: "*"
endpoint:
health:
show-details: ALWAYS
5.启动项目后访问http://127.0.0.1/csdn,之后能正确转发到csdn的话就说明这个Gateway服务启动成功已经能正常转发了。
这里我做了一个返回数据的统一返回格式的处理,后面也会写一篇博客出来的。