如何在springboot中使用zuul实现网关?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
创新互联公司服务项目包括沙坪坝网站建设、沙坪坝网站制作、沙坪坝网页制作以及沙坪坝网络营销策划等。多年来,我们专注于互联网行业,利用自身积累的技术优势、行业经验、深度合作伙伴关系等,向广大中小型企业、政府机构等提供互联网行业的解决方案,沙坪坝网站推广取得了明显的社会效益与经济效益。目前,我们服务的客户以成都为中心已经辐射到沙坪坝省份的部分城市,未来相信会继续扩大服务区域并继续获得客户的支持与信任!1 添加依赖
dependencies { implementation('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client') implementation('org.springframework.cloud:spring-cloud-starter-netflix-zuul') testImplementation('org.springframework.boot:spring-boot-starter-test') implementation('com.marcosbarbero.cloud:spring-cloud-zuul-ratelimit:1.3.2.RELEASE') }
2 添加yml
server: port: 8300 spring: application: name: microservice-gateway-zuul eureka: client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:6761/eureka instance: ip-address: true zuul: routes: users: path: /lind/** #以lind开头的路径被重定向到lind服务 serviceId: lind add-host-header: true #显示真实的http头 retryable: false #关闭Hystrix的重试功能 ratelimit: enabled: true # repository: REDIS behind-proxy: true policies: users: limit: 5 #限流,每分钟请求5次 refresh-interval: 60 type: - user - origin - url # url类型的限流就是通过请求路径区分 # origin是通过客户端IP地址区分 # user是通过授权用户进行区分,也包括匿名用户
3 添加实现代码
http拦截器,获取用户ID,为子服务进行传递
public class PreRequestLogFilter extends ZuulFilter { private static final Logger logger = LoggerFactory.getLogger(PreRequestLogFilter.class); private final RateLimiter rateLimiter = RateLimiter.create(1000.0); @Override public Object run() { try { RequestContext currentContext = RequestContext.getCurrentContext(); HttpServletResponse response = currentContext.getResponse(); HttpServletRequest reqeust = currentContext.getRequest(); currentContext.addZuulRequestHeader("userId","123");//向子系统http头写数据 currentContext.addZuulRequestHeader("userName","test"); PreRequestLogFilter.logger.info( String.format("send %s request to %s", reqeust.getMethod(), reqeust.getRequestURL().toString())); if (!rateLimiter.tryAcquire()) { HttpStatus httpStatus = HttpStatus.TOO_MANY_REQUESTS; response.setContentType(MediaType.TEXT_PLAIN_VALUE); response.setStatus(httpStatus.value()); response.getWriter().append(httpStatus.getReasonPhrase()); currentContext.setSendZuulResponse(false); throw new ZuulException( httpStatus.getReasonPhrase(), httpStatus.value(), httpStatus.getReasonPhrase() ); } } catch (java.lang.Exception e) { ReflectionUtils.rethrowRuntimeException(e); } return null; } @Override public boolean shouldFilter() { // 判断是否需要过滤 return true; } @Override public String filterType() { return FilterConstants.PRE_TYPE; } @Override public int filterOrder() { return Ordered.HIGHEST_PRECEDENCE; } }
在主程中注入这个过滤器
@Bean public PreRequestLogFilter preRequestLogFilter() { return new PreRequestLogFilter(); }
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注创新互联行业资讯频道,感谢您对创新互联的支持。