JAVA中间件(middleware)模式
主要围绕下面几点介绍
-
概念
-
应用场景(对比其他语言)
-
和filter,拦截器,传统的pipeline模式的区别(用forEach代替不了么?)
-
在java中如何实现中间件模式(附源码)
中间件的概念
首先它是一种设计模式,一种功能的封装方式,就是封装在程序中处理复杂业务逻辑的功能。
说概念很难理解,结合应用场景比较好说明
比如在http请求中往往会涉及很多动作, IP筛选, 查询字符串传递, 请求体解析, cookie信息处理, 权限校验, 日志记录 ,会话管理中间件(session), gzip压缩中间件(如compress) ,错误处理等
aspnetcore中处理http请求的也是用的中间件模式,
微软官方文档介绍:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-5.0
nodejs中封装以上http请求细节处理的方法里面用到的就是中间件模式。比如主流的nodejs框架 express ,koa 等
以koa框架为例 middleware的构成是用use方法添加, 下面的代码中添加了一个 日志中间件,一个在response的header中添加'X-Response-Time'(记录请求处理时长)的中间件
const Koa = require('koa');
const app = new Koa();
// logger
app.use(async (ctx, next) => {
await next();//进入下一个中间件
const rt = ctx.response.get('X-Response-Time');
//记录日志
console.log(`${ctx.method} ${ctx.url} - ${rt}`);
});
// x-response-time
app.use(async (ctx, next) => {
const start = Date.now();
await next();//进入下一个中间件
const ms = Date.now() - start;
//记录请求时长
ctx.set('X-Response-Time', `${ms}ms`);
});
// response
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
