Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement Zuul filter in Spring Cloud

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article will explain in detail how to implement the Zuul filter in Spring Cloud. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

Zuul filter priority

Spring Cloud provides multiple filters for each phase of a HTTP request, and the order in which these filters are executed is determined by an int value provided by each of them, and the smaller the value provided, the higher the priority. Figure 7-6 shows the default filters and their priorities.

Figure 7-6 filters and priorities included with Spring Cloud

As shown in figure 7-6, in the routing phase, the filter for Ribbon routing is implemented first, followed by a simple route filter.

Custom filter

After knowing the order in which the filter is executed, we write a custom filter. Create a new filter class and inherit ZuulFilter. See listing 7-10 for the implementation.

Listing 7-10:

Codes\ 07\ 03\ zuul-gateway\ src\ main\ java\ org\ crazyit\ cloud\ filter\ MyFilter.java

Public class MyFilter extends ZuulFilter {/ / filter execution condition public boolean shouldFilter () {return true;} / / execution method public Object run () {System.out.println ("execute MyFilter filter"); return null;} / / indicates that public String filterType () {return FilterConstants.ROUTE_TYPE will be executed during the routing phase } / / return 1, routing phase, this filter will be the first to execute public int filterOrder () {return 1;}}

The newly created custom filter will be executed in the "routing" phase with a priority of 1, that is, in the routing phase, the filter will be executed first. Also note the shouldFilter method, which determines whether the filtering will eventually be performed. This example returns true, which means that the filter will be executed if any routing rules are accessed. In order to let the Spring container know that the filter exists, the class needs to be configured. Listing 7-11 is the configuration class.

Listing 7-11:

Codes\ 07\ 03\ zuul-gateway\ src\ main\ java\ org\ crazyit\ cloud\ filter\ FilterConfig.java

@ Configurationpublic class FilterConfig {@ Bean public MyFilter myFilter () {return new MyFilter ();}}

Start the cluster, access the gateway: http://localhost:8080/test/1, and you will see the control output: "execute MyFilter filter". In fact, accessing any of the configured routes will be output.

Filter dynamic loading

Compared with other nodes in the cluster, gateways need to provide long-term and stable services. If you need to add a filter, it is too expensive to restart the gateway. In order to solve this problem, Zuul provides the dynamic loading function of the filter. You can use Groovy to write the filter, then add it to the loading directory and let Zuul load dynamically. Add Groovy dependencies to the gateway project first:

Org.codehaus.groovy groovy-all 2.4.12

Next, in the application class of the gateway project, call Zuul's API to implement dynamic loading, as shown in listing 7-12.

Listing 7-12:

Codes\ 07\ 03\ zuul-gateway\ src\ main\ java\ org\ crazyit\ cloud\ GatewayApplication.java

@ EnableZuulProxy@SpringBootApplicationpublic class GatewayApplication {@ PostConstruct public void zuulInit () {FilterLoader.getInstance () .setCompiler (new GroovyCompiler ()); / / read the configuration, get the script root directory String scriptRoot = System.getProperty ("zuul.filter.root", "groovy/filters"); / / get the refresh interval String refreshInterval = System.getProperty ("zuul.filter.refreshInterval", "5") If (scriptRoot.length () > 0) scriptRoot = scriptRoot + File.separator; try {FilterFileManager.setFilenameFilter (new GroovyFileFilter ()); FilterFileManager.init (Integer.parseInt (refreshInterval), scriptRoot + "pre", scriptRoot + "route", scriptRoot + "post");} catch (Exception e) {throw new RuntimeException (e) }} public static void main (String [] args) {new SpringApplicationBuilder (GatewayApplication.class). Properties ("server.port=8080") .run (args);}}

In the startup class, the zuulInit method is added, decorated with @ PostConstruct. In this method, the "zuul.filter.root" and "zuul.filter.refreshInterval" attributes are read first, which represent the root directory of the dynamic filter and the refresh interval, respectively, and the refresh interval is in seconds. These two attributes give priority to reading the value of the configuration file, and use the default value if not. In the configuration file, you can use the following configuration snippet:

Zuul: filter: root: "groovy/filters" refreshInterval: 5

Call the init method of FilterFileManager to initialize three filter directories: pre, route, and post. To test dynamic loading, write the simplest filter using Groovy, as shown in listing 7-13.

Listing 7-13:codes\ 07\ 03\ zuul-gateway\ src\ main\ java\ groovy\ filters\ DynamicFilter.groovy

Class DynamicFilter extends ZuulFilter {public boolean shouldFilter () {return true;} public Object run () {System.out.println ("= this is a dynamically loaded filter: DynamicFilter"); return null;} public String filterType () {return FilterConstants.ROUTE_TYPE } public int filterOrder () {return 3;}}

Consistent with the previous filter, it also inherits ZuulFilter. It should be noted that the filter in this example is not initially placed in the dynamically loaded filter directory. When testing, the reader needs to start the gateway project first, and then put the DynamicFilter.groovy in the corresponding directory.

After completing the above work, start the gateway project and visit the following address: http://localhost:8080/test/crazyit. The information of DynamicFilter is not output in the console. Copy the DynamicFilter.groovy to the src/main/java/groovy/filters/route directory, wait a few seconds, and then revisit the above address. You can see the console output of the gateway as follows:

This is a dynamically loaded filter: this is the end of DynamicFilter's article on "how to implement Zuul filter in Spring Cloud". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report