【四】服务网关之Zuul的使用

参考https://blog.csdn.net/hellozpc/article/details/84144453#3__Spring_Cloud_Zuul_243

一、简介

前面已经启动了服务注册Eurake、启动了两个服务item和order

【一】服务调用之服务A用RestTemplate实现以HTTP的方式调用服务B

【二】服务注册之Eureka注册中心使用

【三】服务调用之spring cloud feign使用

本片加入服务网关用Zuul后:

无论是请求item还是order系统,前端都统一访问请求到Zuul,由Zuul根据自己配置的路由规则转发到item或者order上。

有了服务网关后,我们可以在服务网关部分加入权限校验,符合权限校验的才放行到后面的系统中去。

本篇只演示基本的使用,在Zuul再加入拦截去鉴权以后再写。

二、代码

创建项目zuul

【四】服务网关之Zuul的使用_第1张图片

pom.xml



    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.6.RELEASE
    
    4.0.0

    zuul

    
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-zuul
        
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

application.yml

server:
  port: 8087 #服务端口
spring:
  application:
    name: app-zuul #指定服务名
###服务注册到eureka注册中心的地址
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8100/eureka/
    ###因为该应用为服务提供者,是eureka的一个客户端,需要注册到注册中心
    register-with-eureka: true
    ###是否需要从eureka上检索服务
    fetch-registry: true
  instance:
    prefer-ip-address: true #将自己的ip地址注册到Eureka服务中
    ip-address: localhost
    #instance-id: ${spring.application.name}###${server.port} #指定实例id
zuul:
  routes: #定义服务转发规则
    item-service: #item-service这个名字是任意写的
      path: /item-service/** #匹配item-service的请求app-item服务
      #url: http://127.0.0.1:8081 #真正的微服务地址
      serviceid: app-item
    order-service: #名字尽量和业务系统相关
      path: /order-service/** #匹配order-service的请求app-order服务
      serviceid: app-order

启动文件ZuulApp.java

package com.sid;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@EnableZuulProxy
@SpringBootApplication
public class ZuulApp {
    public static void main(String[] args) {
        SpringApplication.run(ZuulApp.class, args);
    }
}

请求zuul的地址http://localhost:8087/item-service/item/2

该请求会被路由到http://127.0.0.1:8081/item/2上(这是在zuul的application.yml配置文件中配置的)

结果:

【四】服务网关之Zuul的使用_第2张图片

 

你可能感兴趣的:(微服务)