注意:springboot版本为2.0
1.描述
客户端请求统一先请求到网关服务器上,再由网关服务器进行转发到实际服务器地址上(类似于Nginx)
1.1 网关作用
网关可以拦截所有请求,对权限进行负载均衡,日志管理,接口调用管理等等。
1.2 nginx和zuul区别
相同点:都可以实现负载均衡,反向代理,过滤请求。
不同点:nginx使用c语言写的 zuul使用java语言写的。
zuul负载均衡:通过ribbon+eureka实现本地负载均衡。
nginx负载均衡:采用服务器端实现
建议使用nginx+zuul方式
1.3 案例
为了安全考虑,一般这些服务只有登录过后才能使用。没有zuul的情况下,一般大家都是在每个服务里面增加一个拦截器,假设,有100个服务,就有100个拦截器。而zuul就能很好的帮我们解决权限的问题,可以理解为一个中级件,减少重复鉴权.
2.代码
因本博客只是简单的gateway的使用,所以,会员服务等代码配置就在本文阐述勒。
2.1 pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--网关-->
<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>
2.2yml配置
####服务器端口号
server:
port: 8060
###服务别名---服务器注册到注册中心的名称
spring:
application:
name: zuul-service
eureka:
client:
###需要将我的服务注册到eureka上
registerWithEureka: true
###检索服务
fetchRegistry: true
###当前服务注册到eureka服务地址
serviceUrl:
defaultZone: http://localhost:8100/eureka/
##设置feign超时时间
ribbon:
##指的是创建连接所用的时间,适用于网络状况正常的情况下,两端所用的时间,默认是1s
ReadTimeout: 3000
##指的是创建连接后从服务器读取可用资源所用的时间
ConnectTimeout: 3000
##开启Hystrix断路器
feign:
hystrix:
enabled: true
zuul:
routes:
member:
##类似于转发
path: /member/**
serviceId: fqyd-member
order:
path: /order/**
serviceId: fqyd-order
routes下一级,例如member和order是对应规则路由,可以理解为某个服务
path: 是反向代理访问地址。可以理解为nginx里面的代理。
serviceId: 对应服务的名称(一定要保证一致)
2.3 启动类
package com.fqyd;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* Description:
* Author: wude
* Date: 2019/7/25 16:49
* Modified By:
*/
@SpringBootApplication
@EnableZuulProxy
@EnableEurekaClient
public class ZuulServiceImplApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulServiceImplApplication.class,args);
}
}
2.4 会员服务
3 测试
不增加网关,直接访问服务
增加网关,通过网关访问,这里的端口是网关的端口,member就是网关配置里面的path的值。
4.问题
为什么要用网关?
使用网关可以反向代理,隐藏服务器真实ip和端口,安全系数更高
怎么实现?
一般网关和服务都在一个局域网内
内网: 知道服务ip和服务器端口,影响不大
外网: 如果服务器ip和服务器端口,被泄露,就可以绕过网关直接访问服务,这就减少勒鉴权的过程。
一般外网环境下,建议,只开放网关等固定端口,这样安全系统更高。