一、新增demo_eureka模塊,並編寫代碼
右鍵demo_parent->new->Module->Maven,選擇Module SK為jdk8->ArtifactId:demo_zuul
1.修改pom.xml文件
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>demo_parent</artifactId> <groupId>com.demo</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>demo_zuul</artifactId> <dependencies>
<!-- 服務網關依賴 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId> </dependency>
<!-- eureka客服端依賴 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> </dependencies> </project>
2.在resources目錄下新增application.yml文件
server: port: 8888 spring: application: name: demo-zuul zuul: routes: # 配置路由 app: # 路由名稱,這是一個標識作用,只要是[a-z]可隨意,沒有什么影響 path: /myarticle/* #匹配以/myarticle路徑開頭的所有路徑 serviceId: demo-article #只要符合path規則,則轉發到demo-article微服務 eureka: client: fetch-registry: true register-with-eureka: true service-url: defaultZone: http://127.0.0.1.181:7000/eureka #在IDEA中運行時使用127.0.0.1,部署發布時,請修改為虛擬機宿主機的ip地址 instance: prefer-ip-address: true
3.新建com.demo.zuul包,並在該包下新建啟動類ZuulApplication
package com.demo.zuul; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; /** * 微服務網關 */ @SpringBootApplication // 標注啟動zuul網關代理 @EnableZuulProxy // 標注eureka客戶端 @EnableEurekaClient public class ZuulApplication { public static void main(String[] args) { SpringApplication.run(ZuulApplication.class, args); } }
4.運行ZuulApplication啟動類
刷新eureka界面,可以看到有一個名為DEMO-ZUUL的服務已經注冊上來了