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,为子服务进行传递
publicclassPreRequestLogFilterextendsZuulFilter{ privatestaticfinalLoggerlogger=LoggerFactory.getLogger(PreRequestLogFilter.class); privatefinalRateLimiterrateLimiter=RateLimiter.create(1000.0); @Override publicObjectrun(){ try{ RequestContextcurrentContext=RequestContext.getCurrentContext(); HttpServletResponseresponse=currentContext.getResponse(); HttpServletRequestreqeust=currentContext.getRequest(); currentContext.addZuulRequestHeader("userId","123");//向子系统http头写数据 currentContext.addZuulRequestHeader("userName","test"); PreRequestLogFilter.logger.info( String.format("send%srequestto%s", reqeust.getMethod(), reqeust.getRequestURL().toString())); if(!rateLimiter.tryAcquire()){ HttpStatushttpStatus=HttpStatus.TOO_MANY_REQUESTS; response.setContentType(MediaType.TEXT_PLAIN_VALUE); response.setStatus(httpStatus.value()); response.getWriter().append(httpStatus.getReasonPhrase()); currentContext.setSendZuulResponse(false); thrownewZuulException( httpStatus.getReasonPhrase(), httpStatus.value(), httpStatus.getReasonPhrase() ); } }catch(java.lang.Exceptione){ ReflectionUtils.rethrowRuntimeException(e); } returnnull; } @Override publicbooleanshouldFilter(){ //判断是否需要过滤 returntrue; } @Override publicStringfilterType(){ returnFilterConstants.PRE_TYPE; } @Override publicintfilterOrder(){ returnOrdered.HIGHEST_PRECEDENCE; } }
在主程中注入这个过滤器
@Bean publicPreRequestLogFilterpreRequestLogFilter(){ returnnewPreRequestLogFilter(); }
4使用它
在URL上通过localhost:8300/users/home将进行lind服务里的home控制器下,并在http头上写入了userid和username这个键值对!
总结
以上所述是小编给大家介绍的springbootzuul实现网关,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!