一、基本配置
1、创建gateway微服务
2、引入zuul依赖
<!--引入zuul-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
3、写启动类,并在启动类上添加注解(@EnableZuulProxy)
package cn.itcast;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@EnableZuulProxy
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class);
}
}
4、写配置文件
zuul:
routes:
# path: /user-service/**
# url: user-service
# 服务id:服务的映射路径(默认提供)
# zuul默认提供了所有服务的如下的配置,因此下面这句可以不写
user-service: /user-service/**
# zuul默认提供了所有服务的如上的配置,如果那个服务不想向外暴露,可用如下配置忽略
ignored-services:
- consumer-service
二、自定义过滤器
package cn.itcast.filter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
@Component
public class LoginFilter extends ZuulFilter {
@Override
public String filterType() {
return FilterConstants.PRE_TYPE;
}
@Override
public int filterOrder() {
return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() throws ZuulException {
//获取请求上下文
RequestContext ctx = RequestContext.getCurrentContext();
//获取request
HttpServletRequest request = ctx.getRequest();
//获取请求参数access-token
String token = request.getParameter("access-token");
//判断是否存在
if(StringUtils.isBlank(token)){
//不存在,未登录,拦截
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
}
return null;
}
}
三、负载均衡和熔断
配置文件中添加:
ribbon:
ConnectionTimeout: 500
ReadTimeout: 2000
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 6000