Skip to content

Commit b63cd5f

Browse files
通过zuul进行服务过滤
1 parent 197254f commit b63cd5f

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

zuul/src/main/java/com/example/demo/ZuulApplication.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,21 @@
11
package com.example.demo;
22

3+
import com.example.demo.filter.AccessFilter;
34
import org.springframework.boot.SpringApplication;
45
import org.springframework.boot.autoconfigure.SpringBootApplication;
56
import org.springframework.cloud.client.SpringCloudApplication;
67
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
8+
import org.springframework.context.annotation.Bean;
79

810
@EnableZuulProxy
911
@SpringCloudApplication
1012
public class ZuulApplication {
1113

14+
@Bean
15+
public AccessFilter accessFilter() {
16+
return new AccessFilter();
17+
}
18+
1219
public static void main(String[] args) {
1320
SpringApplication.run(ZuulApplication.class, args);
1421
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.example.demo.filter;
2+
3+
import com.netflix.zuul.ZuulFilter;
4+
import com.netflix.zuul.context.RequestContext;
5+
import org.apache.log4j.Logger;
6+
7+
8+
import javax.servlet.http.HttpServletRequest;
9+
10+
11+
public class AccessFilter extends ZuulFilter {
12+
private static Logger log=Logger.getLogger(AccessFilter.class);
13+
14+
@Override
15+
public String filterType() {
16+
return "pre";
17+
}
18+
19+
@Override
20+
public int filterOrder() {
21+
return 0;
22+
}
23+
24+
25+
@Override
26+
public boolean shouldFilter() {
27+
return true;
28+
}
29+
30+
/**
31+
* 设置过滤。url只有带有有效参数才可以访问。
32+
* @return
33+
*/
34+
@Override
35+
public Object run() {
36+
RequestContext ctx = RequestContext.getCurrentContext();
37+
HttpServletRequest request = ctx.getRequest();
38+
39+
log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));
40+
41+
Object accessToken = request.getParameter("accessToken");
42+
if(accessToken == null) {
43+
log.warn("access token is empty");
44+
ctx.setSendZuulResponse(false);
45+
ctx.setResponseStatusCode(401);
46+
return null;
47+
}
48+
log.info("access token ok");
49+
return null;
50+
}
51+
}

0 commit comments

Comments
 (0)