大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺
1、zuul网关服务
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.yzm</groupId>
<artifactId>springcloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>zuul</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>zuul</name>
<description>Demo project for Spring Boot</description>
<dependencies>
<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>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
启动类
@EnableZuulProxy:启用zuul网关代理
@EnableZuulProxy
@EnableEurekaClient
@SpringBootApplication
public class ZuulApplication {
。。。
}
application.yml
server:
port: 8096
spring:
application:
name: service-zuul
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8088/eureka/
zuul:
routes:
ribbon-ha: /api-a/** ribbon-hi: path: /api-b/** feign_haha: serviceId: feign-ha path: /api-c/**
路由规则:
请求url带有 /api-a/ 的路由到 ribbon-ha 服务(spring.application.name)
请求url带有 /api-b/ 的路由到 ribbon-hi 服务
请求url带有 /api-c/ 的路由到 feign-ha 服务(feign_haha 别名)
2、路由转发
依次启动 eureka、zuul、ribbon-ha、ribbon-hi、feign-ha、feign-hi
http://localhost:8096/api-a/hello?name=yzm
http://localhost:8096/api-b/hello?name=yzm
http://localhost:8096/api-c/hello?name=yzm
配置文件中zuul没有配置feign-hi的路由,但zuul有个默认路由规则即:zuul_ip:zuul_post/service_id/url
http://localhost:8096/feign-hi/hello?name=yzm
所有请求都可以通过zuul正确路由到对应的服务上
二级路由
http://localhost:8096/api-a/ha?name=yzm
转发完成!
再启动ribbon-hi:18093
刷新
负载均衡!
3、zuul配置
url
zuul:
routes:
ribbon-ha: /api-a/** ribbon-hi: path: /api-b/** # feign_haha: # serviceId: feign-ha # path: /api-c/** feign_haha: path: /api-c/** # 转发到IP地址 url: http://localhost:8094/ baidu: path: /baidu/** # 转发到域名 url: https://www.baidu.com/
http://localhost:8096/api-c/hello?name=yzm
http://localhost:8096/baidu/
虽然url也可以进行转发但是无法进行负载均衡,推荐使用serviceId进行配置
ignored
zuul:
ignored-services: '*'
ignored-patterns: /**/hello/** routes: ribbon-ha: /api-a/** ribbon-hi: path: /api-b/** feign_haha: serviceId: feign-ha path: /api-c/**
ignored-services:忽略服务,只接受routes列表中的服务,默认规则的IP:PORT/serviceid/这种就无法转发
ignored-patterns: 忽略请求中带有hello的转发
prefix
zuul:
prefix: /yzm
# 对所有服务有效
# stripPrefix: false
routes:
ribbon-ha: /api-a/** ribbon-hi: path: /api-b/** feign_haha: serviceId: feign-ha path: /api-c/** # 只对feign-ha服务有效 stripPrefix: false
prefix:带有前缀的请求才会被拦截
stripPrefix:默认true,增加的前缀在转发之前剔除,false不剔除
没有前缀不拦截
多了前缀,没有对应接口,访问失败
4、回调
zuul:
ignored-services: '*'
routes:
ribbon-ha: /api-a/** ribbon-hi: path: /api-b/** feign_haha: serviceId: feign-ha path: /api-c/**
拦截api-a请求路由到ribbon-ha时,ribbon-ha服务挂了,此时显示
编写回调
package com.yzm.zuul.filter;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
@Component
public class MyFallbackProvider implements FallbackProvider {
@Override
public String getRoute() {
// 服务id,如果需要所有调用都支持回退,则return "*"或return null
return "ribbon-ha";
}
@Override
public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
return new ClientHttpResponse() {
@Override
public HttpStatus getStatusCode() throws IOException {
return HttpStatus.OK;
}
@Override
public int getRawStatusCode() throws IOException {
return HttpStatus.OK.value();
}
@Override
public String getStatusText() throws IOException {
return HttpStatus.OK.getReasonPhrase();
}
@Override
public void close() {
}
@Override
public InputStream getBody() throws IOException {
String msg = route + ": 服务异常";
return new ByteArrayInputStream(msg.getBytes(StandardCharsets.UTF_8));
}
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
return headers;
}
};
}
}
重启zuul,再次访问
5、过滤器
- filterType:返回一个字符串代表过滤器的类型,在zuul中定义了四种不同生命周期的过滤器类型,具体如下:
- pre:路由之前
- routing:路由之时
- post: 路由之后
- error:发送错误调用
- filterOrder:过滤的顺序,数值越小优先级越高
- shouldFilter:这里可以写逻辑判断,是否要过滤,本文true,永远过滤。
- run:过滤器的具体逻辑。可用很复杂,包括查sql,nosql去判断该请求到底有没有权限访问。
package com.yzm.zuul.filter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
@Slf4j
@Component
public class MyFilter 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();
HttpServletRequest request = ctx.getRequest();
log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
Object accessToken = request.getParameter("token");
if (accessToken == null) {
log.warn("token is empty");
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(401);
try {
ctx.getResponse().getWriter().write("token is empty");
} catch (Exception e) {
//
}
return null;
}
log.info("ok");
return null;
}
}
上面的过滤器要求,请求中必须带有token参数
重启zuul,不带token访问
带token
相关链接
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/170633.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...