1、Nginx与Zuul的区别
相同点:Zuul和Nginx都可以实现负载均衡、反向代理(隐藏真实ip地址),过滤请求,实现网关的效果
不同点:Nginx--c语言开发
Zuul--java语言开发
Zuul负载均衡实现:采用ribbon+eureka实现本地负载均衡
Nginx负载均衡实现:采用服务器实现负载均衡
Nginx相比zuul功能会更加强大,因为Nginx整合一些脚本语言(Nginx+lua)
Nginx适合于服务器端负载均衡
Zuul适合微服务中实现网关
Zuul 因为是java 写的,所以框架设计的更容易些
2,
zuul,projectA,projectB 全都要注册到注册中心eureka上,让eureka 来管控:
step1: 简历eureka 服务
server:
port: 8100
eureka:
instance:
hostname: server1
client:
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
register-with-eureka: false
fetch-registry: false
启动类:
package com.aiyuesheng; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class EurekaApplication { public static void main(final String[] args) { SpringApplication.run(EurekaApplication.class, args); } }
step2: projectA
server:
port: 8000
spring:
application:
name: projectA
eureka:
client:
service-url:
defaultZone: http://localhost:8100/eureka
启动类:
@SpringBootApplication @EnableDiscoveryClient public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
controller:
@RestController public class Index { @RequestMapping("/") public String index() { return "PROJECTA"; } }
step2: projectB
server:
port: 8001
spring:
application:
name: projectB
eureka:
client:
service-url:
defaultZone: http://localhost:8100/eureka
启动类:
@SpringBootApplication @EnableDiscoveryClient public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
controller:
@RestController
public class Index {
@RequestMapping("/")
public String index() {
return "PROJECTB";
}
}
step4: zuul 配置网关
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8100/eureka/
server:
port: 8080
spring:
application:
name: service-zuul
zuul:
routes:
projectA:
path: /projectA/**
serviceId: projectA
projectB:
path: /projectB/**
serviceId: projectB
zuul:
routes:
api-a:
path: /api-a/**
serviceId: itmayiedu_a
api-b:
path: /api-b/**
serviceId: itmayiedu_b
启动类:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.context.annotation.Bean; @EnableZuulProxy @SpringBootApplication @EnableDiscoveryClient public class ZuulApplication { public static void main(String[] args) { SpringApplication.run(ZuulApplication.class, args); } // @Bean // public TokenFilter accessFilter() { // return new TokenFilter(); // } }
先启动eureka 注册中心,再启动其他三个服务,启动之后,可以web 页面查看服务是否注册上去:
我就可以通过网关配置的routes
routes:
projectA:
path: /projectA/**
serviceId: projectA
projectB:
path: /projectB/**
serviceId: projectB
127.0.0.1/projectA 就自动跳到A项目
127.0.0.1/projectB 就自动跳到B项目