2022-02-14
springcloud~gateway网关
                来源:博客园    时间:2023-05-23 13:14:59              
            
(资料图片)
有时间,我们在搭建微服务时,总希望拿一个比较单纯的,没有污染其它代码的项目来从头开始做,今天我们来建设一个最简单的,gateway项目,它被注册到nacos里,路由配置也存到nacos里,动态实现更新配置功能。
依赖配置
版本:com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-discovery:2021.0.1.0,com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-config:2021.0.1.0,org.springframework.cloud:spring-cloud-starter-gateway:3.1.3
                    com.alibaba.cloud             spring-cloud-starter-alibaba-nacos-discovery                              com.alibaba.cloud             spring-cloud-starter-alibaba-nacos-config                              org.springframework.cloud             spring-cloud-starter-gateway                                    org.springframework.cloud             spring-cloud-starter-bootstrap                                    org.springframework.cloud             spring-cloud-loadbalancer               bootstrap.yml配置
spring:  application:    name: lind-gateway  cloud:    nacos:      config:        server-addr: 192.168.xx.xx:8848        groupId: DEFAULT_GROUP        namespace: public        file-extension: yaml #对应nacos上面的配置文件扩展名      discovery:        server-addr: 192.168.xx.xx:8848logging:  level:    root: warn    org.springframework.cloud.gateway: debug #日志级别,方便调试    org.alibaba.nacos: debugnacos里的lind-gateway.yaml配置
spring:  cloud:    gateway:      discovery:        locator:          enabled: true      routes:      - id: micro-product        uri: lb://micro-product        predicates:          - Path=/product/**      - id: micro-account        uri: lb://micro-account        predicates:          - Path=/account/**      - id: micro-order        uri: lb://micro-order        predicates:          - Path=/order/**      default-filters:        - StripPrefix=1 #请求地址去掉第1位,例如你请求/product/md/create时,实际转发到micro-product服务里的接口是/md/create需要注意的地方
- pom引用包时,需要添加spring-cloud-loadbalancer,以在gateway中实现负载协议
 - 使用nacos配置时,需要添加spring-cloud-starter-bootstrap
 - 如果是多级路径转发,加载添加StripPrefix,将可以在转发到后端时,将路径的前几位去除
 
测试
- 调用micro-product中的接口:http://localhost:8080/product/stock/deduct?commodityCode=product-1&count=1
 - 接口代码
 
@RequestMapping(path = "/stock/deduct")public Boolean deduct(String commodityCode, Integer count) {stockService.deduct(commodityCode, count);return true;}- 正常响应
 
标签:
                世界快报:浙江省农业“双强”专班来舟山开展调研服务
                
              
                  
                     << 上一篇
                
              
                最后一页
                
            
                  
                   下一篇 >>
                
              - 精心推荐
 
X 关闭
X 关闭



