目录
好了,不知不觉中我们已经来到了最后一篇文章,也来到了最一个工程"mirco-service-zuul",zuul是一个服务网关,虽然现在spring也出了spring cloud gateway,相信有很多之前就使用spring cloud的公司依然使用的是zuul;看完这六篇文章相信有点基础的小伙伴们应该能自己做点东西了,当然spring cloud这个系列远远还没有说完,后面我计划在春节前后开源一个最小化的微服务手脚架项目,使用spring cloud来做实战演练。
因为api网关是一个比较独立的东西,基本不需要对原有的工程进行改造。
server: port: 5001 spring: application: name: service-gateway-zuul zuul: routes: baidu: url: http://www.baidu.com path: /api/**
启动服务,访问http://localhost:5001/api/,你会看到页面重定向到百度了。那么我们zuul的配置就完了。
server: port: 5001 spring: application: name: service-gateway-zuul eureka: client: service-url: defaultzone: http://localhost:9001/eureka/
@enablediscoveryclient @enablezuulproxy @springbootapplication public class mircoservicezuulapplication { public static void main(string[] args) { springapplication.run(mircoservicezuulapplication.class, args); } }
因为服务化改造后,zuul会自动代理所有eureka上的服务,访问格式如下:
http://localhost:5001/{service-id}/{app-path}
api网关中,可以在请求被路由之前调用,四种状态 pre、routing、post、error,这四种状态的意思大家可以自行去了解一下。我们要使用的是pre状态。
public class validatetokenfilter extends zuulfilter{ @override public boolean shouldfilter() { // 是否执行此过滤 return true; } @override public object run() throws zuulexception { // 处理过程 requestcontext context = requestcontext.getcurrentcontext() ; httpservletrequest request = context.getrequest() ; boolean bool = boolean.valueof(request.getparameter("token")) ; if(bool) { context.setsendzuulresponse(true) ; //是否路由 context.setresponsestatuscode(200); context.set("issuccess", true); }else { context.setsendzuulresponse(false) ; //是否路由 context.setresponsestatuscode(400); context.set("issuccess", false); } return null; } @override public string filtertype() { return "pre"; // 可以在请求被路由之前调用,四种状态 pre、routing、post、error } @override public int filterorder() { // 执行顺序 return 10; } }
@bean public zuulfilter putfilter() { return new validatetokenfilter() ; }
如对本文有疑问, 点击进行留言回复!!
【奥鹏作业答案库网】大工20春《应用统计》在线作业1【奥鹏作业答案】
网友评论