This is the 29th day of my participation in the August More Text Challenge

introduce

Zuul, a member of Netflix OSS, is a LOAD balancer based on JVM routing and server side. Provides a service framework for routing, monitoring, elasticity, and security. Zuul works with Eureka, Ribbon, Hystrix and more.

role

1) Dynamic routing

Dynamically route client requests to different back-end services, doing some logical processing, such as aggregating data returns from multiple services.

2) Request monitoring

You can monitor requests of the entire system, record detailed request response logs, and obtain real-time statistics of the current system access volume and monitoring status.

3) Authentication and authentication

Authenticate every access request, reject illegal requests, and protect backend services.

4) Stress test

Stress testing is a very important work, like some e-commerce companies need to simulate more real user concurrency to ensure the stability of the system during major events. Zuul allows you to dynamically forward requests to a cluster of back-end services and to identify test traffic and real traffic for special processing.

5) Grayscale release

Grayscale publishing can ensure the stability of the whole system, and problems can be found and adjusted at the beginning of the grayscale to ensure its impact.

6) Reduce client-server coupling

Services can evolve independently and are mapped through the gateway layer.

7) Unified entrance

Providing a unique entrance for all services, the gateway plays the role of external and internal isolation, ensuring the security of background services.

Zuul and Nginx

Above is the usage introduction of zuul, we can see that its usage is very similar to Nginx, and again I have made some personal comments about them.

  • Similarities:

Zuul and Nginx can both implement load balancing, reverse proxy (hiding real IP addresses), filter requests, and act like gateways

  • Difference:

1)Nginx uses C language development and Zuul uses Java language development.

2) Load balancing :Zuul uses the Ribbon + Eureka to achieve local load balancing. Nginx uses servers for load balancing.

3)Nginx is more powerful than Zuul because Nginx integrates some scripting languages (Nginx+ Lua).

4) Action scenario: Nginx is suitable for server-side load balancing, Zuul is suitable for micro services to implement the gateway.

Setting up gateway Scenarios

Maven robust introduction

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
Copy the code

Configuration of YML files. The following functions can intercept the contents of the path shop/** and go directly to www.baidu.com.

  • Note: Zuul’s API routing also provides local jumps, which can be implemented by forward.

zuul.routes.fsh-substitution.path=/api/**

zuul.routes.fsh-substitution.url=forward:/local

spring: application: name: zuul-demo server: port: 3366 zuul: # # the prefix: / API routing prefix add http://localhost:3366/shop/1 login interface, if you want to turn it into http://localhost:3366/api/shop/1 routes: # FSH - house: # path: / API /** If only one asterisk is configured, then only one level can be forwarded, such as "/ API /shop". Biancheng: path: /shop/** #Copy the code

We will then add the @enableZuulProxy proxy annotation to the Tomcat startup class

@EnableZuulProxy @SpringBootApplication public class ZuulMain3366 { public static void main(String[] args) { SpringApplication.run(ZuulMain3366.class, args); }}Copy the code

Above we can realize a simple block, we can visit http://localhost:3366/shop/1 the browser will automatically jump to the link www.baidu.com page.

Filter type

introduce

The filters in Zuul are not the same as the filters I wrote in the interceptors I wrote earlier. There is only one type of Filter and you can configure urlPatterns to intercept the corresponding requests. There are four types of filters in Zuul, and each type has its own usage scenario.

1) the pre

Can be called before the request is routed. This method applies to identity authentication scenarios. Perform the following operations after the authentication succeeds.

2) the route

Called when routing a request. Suitable for grayscale publishing scenarios, you can do some custom logic when routing.

3) post

Called after route and error filters. This filter will be executed after the request routes to the specific service. This mode applies to the scenarios where response headers are added and response logs are recorded.

4) the error

Called when an error occurs while processing a request. Error filters are entered when errors are sent during execution, which can be used to uniformly record error information.

ZuulService

@Override public void service(javax.servlet.ServletRequest servletRequest, javax.servlet.ServletResponse servletResponse) throws ServletException, IOException { try { init((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse); RequestContext context = RequestContext.getCurrentContext(); context.setZuulEngineRan(); try { preRoute(); } catch (ZuulException e) { error(e); postRoute(); return; } try { route(); } catch (ZuulException e) { error(e); postRoute(); return; } try { postRoute(); } catch (ZuulException e) { error(e); return; } } catch (Throwable e) { error(new ZuulException(e, 500, "UNHANDLED_EXCEPTION_" + e.getClass().getName())); } finally { RequestContext.getCurrentContext().unset(); }}Copy the code

Use filters

We created a Pre filter to filter the blacklist IP (“192.168.0.157”).

Public class IpFilter extends ZuulFilter {// IP blacklist private List<String> blackIpList = array.asList ("192.168.0.157");  public IpFilter() { super(); } @Override public boolean shouldFilter() { return true } @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 1; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); String ip = IpUtils.getIpAddr(ctx.getRequest()); // Disable if (stringutils.isnotBlank (IP) && Blackiplist. contains(IP)) {ctx.setSendZuulResponse(false); ResponseData = responsedata.fail (" currently invalid request: ", responseode.no_auth_code.getCode ()); ctx.setResponseBody(JsonUtils.toJson(data)); ctx.getResponse().setContentType("application/json; charset=utf-8"); return null; } return null; }}Copy the code

1) shouldFilter

Whether to execute the filter, true means to execute, false means not to execute, this can also be implemented using the configuration center, to dynamically enable and disable the filter.

2) filterType

Filter type. Possible values are Pre, route, POST, or error.

3) filterOrder

Filter execution sequence. A smaller value indicates a higher priority.

4) run

Execute their own business logic, this section of code is to determine whether the REQUEST IP is in the blacklist, decide whether to intercept. The blackIpList field is a blacklist of IP addresses. If the condition is correct, set ctx.setSendZuulResponse (false) to tell Zuul that the current request does not need to be forwarded to the back-end service. The setResponseBody returns data to the client.

Injection puts the filter into effect

@Configuration public class FilterConfig { @Bean public IpFilter ipFilter() { return new IpFilter(); }}Copy the code

The above is part of the use of Zuul. As long as you read the article “Filter” I wrote before, you can solve the same problem to solve exceptions, errors and other unified processing. You can understand, I will not say more here.

Handwriting is not easy, we still need to give a lot of praise and attention, the students who like technology do not be impatient, this series of articles I will gradually launch, we all study together.