使用zuul可以对微服务提供的api进行路由和保护。本节将阐述zuul在微服务中的两种用法:路由和过滤。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
注意:springboot的版本是2.1.8.RELEASE,springcloud的版本是Greenwich.SR2
server.port=8003
eureka.client.service-url.defaultZone=http://localhost:7561/eureka
spring.application.name=zuul-service
zuul.routes.traditional-url.path=/api/url/**
zuul.routes.traditional-url.url=http://localhost:8001
zuul.routes.orient-service-url.path=/api/service/**
zuul.routes.orient-service-url.service-id=provider-service
zuul.prefix=/wanho
@EnableEurekaClient
@EnableZuulProxy
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
@Component
public class PasswordFilter extends ZuulFilter {
@Override
public String filterType() {
return "post"; // 请求处理完成后执行的filter
}
@Override
public int filterOrder() {
return 1; // 优先级为0,数字越大,优先级越低
}
@Override
public boolean shouldFilter() {
boolean enable = true;//为true一定会执行run
return enable;
}
@Override
public Object run() throws ZuulException {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
String password= request.getParameter("password");
if(StringUtils.isEmpty(password) || !password.equalsIgnoreCase("123456")){
//不放行
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(500);
ctx.setResponseBody("password is empty");
return null;
}else{
//放行
ctx.setSendZuulResponse(true);
ctx.setResponseStatusCode(200);
return null;
}
}
}
原文:https://www.cnblogs.com/alichengxuyuan/p/12581317.html