1.添加依赖
org.springframework.cloud
spring-cloud-starter-zuul
org.springframework.cloud
spring-cloud-starter-eureka
2.入口程序添加注解@EnableZuulProxy
@SpringBootApplication
@EnableZuulProxy
public class MicroserviceGetwayZuulApplication {
public static void main(String[] args) {
SpringApplication.run(MicroserviceGetwayZuulApplication.class, args);
}
}
3.设置配置文件
3.1 配置eureka客户端和日志配置
spring:
application:
name: microservice-getway-zuul
server:
port: 8070
eureka:
client:
healthcheck:
enabled: true
serviceUrl:
defaultZone: http://user:1234@localhost:8761/eureka
instance:
prefer-ip-address: true
instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
logging:
level:
com.netflix: debug # 配置该级别可以查看前后端url的转换结果日志
3.2 zuul的配置说明
一
zuul:
routes:
microservice-consumer-hystrix: /consumer/**
#表示只要HTTP请求是 /consumer开始的,就会forward到服务id为microservice-consumer-hystrix的服务上面
#没有配置在routes的微服务,默认为添加appname为前缀,类似默认添加配置zuul.routes.microservice-consumer-hystrix:/microservice-consumer-hystrix/**
二
zuul:
ignoredServices: '*'
routes:
microservice-consumer-hystrix: /consumer/**
三
zuul:
routes:
abc:
path: /consumer/**
serviceId: microservice-consumer-hystrix #填写微服务的serviceId
#url:http://localhost:9000 与serviceId相同意思,填写微服务地址端口链接
四
@SpringBootApplication
@EnableZuulProxy
public class MicroserviceGetwayZuulApplication {
// servicePattern: 指的是微服务的pattern
// routePattern: 指的是路由的pattern
@Bean
public PatternServiceRouteMapper serviceRouteMapper() {
return new PatternServiceRouteMapper("(?^.+)-(?v.+$)", "${version}/${name}");
}
public static void main(String[] args) {
SpringApplication.run(MicroserviceGetwayZuulApplication.class, args);
}
}
上方配置的效果如下:
如果微服务的appname设置为microservice-consumer-hystrix-v1
则访问的路径则为localhost:8070/v1/microservice-consumer-hystrix/movief/1
五
zuul:
routes:
abc:
path: /consumer/**
service-id: microservice-consumer-hystrix
ribbon:
eureka:
enabled: false
microservice-provider-user: # 这边是ribbon要请求的微服务的serviceId
ribbon:
listOfServers: http://localhost:8031,http://localhost:8032
六
zuul:
ignoredServices: '*'
routes:
microservice-consumer-hystrix: /consumer/**
prefix: /api
api/consumer/movief/1 转变为 movief/1
zuul:
ignoredServices: '*'
routes:
abc:
path: /consumer/**
serviceId: microservice-consumer-hystrix #填写微服务的
# strip-prefix: false 只用于abc
prefix: /movief
strip-prefix: false #全局使用
movief/consumer/1 转变为 movief/1
七
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 60000
ribbon:
ConnectTimeout: 3000
ReadTimeout: 60000
VM options: -server -XX:PermSize=512M -XX:MaxPermSize=1024M
curl -F “[email protected]” localhost:8070/microservice-file-upload/upload