网关相关配置
小型项目网关配置
(不需要中间件 nacos,consul,Eureka)
只需要 服务路由以及服务发现(注册)即可。
结构: spring.cloud.gateway
routes
配置路由
uri:路由目的地 服务
predicates:谓词,规则
-Path :请求匹配路径
-name:读取请求体
args:
inClass:将请求体转换为字符串【前提是能转换,如果转换失败,则网关报错,将这个请求拦截,不让继续路由转发,正常业务中,传递的都是json字符串,所以inClass一般是指定为String或Object类型】
针对上面的inClass字段,我这里手贱指定为Integer类型,则会报错:
org.springframework.web.server.ServerWebInputException: 400 BAD_REQUEST "Failed to read HTTP message"; nested exception is org.springframework.core.codec.DecodingException: JSON decoding error: Cannot deserialize value of type `java.lang.Integer` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.lang.Integer` from Object value (token `JsonToken.START_OBJECT`)
predicate:自定义predicate接口,我们可以编写实现类,去写一些逻辑,比如针对请求头、请求体里面的字段...
filters:
-RewritePath = 路径A , 路径B 将路径A 替换为路径B ,经常结合正则表达式
对于同一接口,根据不同参数字段,去路由到不同服务,也可以在predicates中指定Header的字段
底层其实是将predicates下的一行行信息,转换成RouteDefinition对象,然后再分割成数组,最后被封装成一个个PredicationDefinition对象,放到list中
discovery
服务注册,将来我需要路由的服务先注册到本地【通过client.simple.instances】
两个定义的内容是一样的,serviceId表明当前服务的唯一ID,instanceId表明当前服务下可能存在多个实例,保证每个实例唯一。