1.首先新建一个Module:
- 选择好依赖。 2.在启动引导类上加上启用zuul组件的注解:
@EnableZuulProxy //启用zuul组件
3.配置application.yml文件:
server:
port: 10010
spring:
application:
name: itwei-zuul
zuul:
routes:
service-provider: #路由名称,可以随便写,习惯上服务名
path: /service-provider/** #url上写的路径
url: http://localhost:8082
4.然后就可以通过zuul网关来访问服务提供方的服务:
- 服务提供方: 但是这样我们发现url都写死了,所以我们要对zuul进行改造。
5.将zuul注入到eureka容器:
分三步:
- 1.引入pom依赖:
<!-- 引入eureka依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
- 2.引导类上添加注解:
@EnableDiscoveryClient //开启eureka客户端
- 3.修改application.yml配置文件:
server:
port: 10010
spring:
application:
name: itwei-zuul
zuul:
routes:
service-provider: #路由名称,可以随便写,习惯上服务名
path: /service-provider/** #url上写的路径
#url: http://localhost:8082
serviceId: service-provider #eureka中服务名
eureka: #配置要注入的eureka容器
client:
service-url:
defaultZone: http://localhost:10086/eureka
4.最后运行代码:
5.可以简化application.yml配置文件:
server:
port: 10010
spring:
application:
name: itwei-zuul
zuul:
routes:
service-provider: /service-provider/** #路由名称,可以随便写,习惯上服务名
eureka:
client:
service-url:
defaultZone: http://localhost:10086/eureka
6.最简化application.yml配置文件:
server:
port: 10010
spring:
application:
name: itwei-zuul
eureka:
client:
service-url:
defaultZone: http://localhost:10086/eureka
默认直接根据注入到eureka容器中的服务名为url。
**server:
port: 10010
spring:
application:
name: itwei-zuul
zuul:
routes:
service-provider: /user/** #前面为注入到eureka的服务名,后面为输入时添加的前缀
service-consumer: /consumer/**
prefix: /api #统一再增加前缀
eureka:
client:
service-url:
defaultZone: http://localhost:10086/eureka**
7.推荐还是需要配置一下滴:
server:
port: 10010
spring:
application:
name: itwei-zuul
zuul:
routes:
service-provider: /user/** #前面为注入到eureka的服务名,后面为输入时添加的前缀
service-consumer: /consumer/**
prefix: /api #统一再增加前缀
eureka:
client:
service-url:
defaultZone: http://localhost:10086/eureka
8.运行结果:
- 服务提供方:
- 服务调用方: