JAVA中间件(middleware)模式

 

  • ()

  • filter,pipeline(forEach)

  • java()

http, IP   cookie   (session) gzip(compress) 

aspnetcorehttp 

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-5.0

nodejshttpnodejs express koa 

koa middlewareuse  responseheader'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);
复制代码

 

  

 

  • 3000web

  • http://localhost:3000

  • logger

  • loggernext()  x-response-time

  •  next()  reponse helloword

  • x-response-time

  • logger

next()next

filterpipeline()

filter 


//java伪代码

for (Filter filter : myFilters){
  filter.excute(xx)
}

//要么是在组织调用的地方加判断
for (Filter filter : myFilters){
  bool continueRun = filter.excute(xx)
  if(!continueRun) break;
}

filter

java

 

  • use()

@FunctionalInterface
public interface Middleware {
     void excute(MiddlewareContext ctx, MiddlewareNext next);
}

 



2

复制代码
/**
 * 中间件方法的参数
 * 上下文
 */
public class MiddlewareContext {
    private final Map<String,Object> contextMapObjectCache;

    public MiddlewareContext() {
        contextMapObjectCache = new HashMap<>();
    }
    public <T> void set(String key,T value) {
        contextMapObjectCache.put(key,value);
    }
    public <T> T get(String key){
        if(contextMapObjectCache.containsKey(key)){
            return (T)contextMapObjectCache.get(key);
        }
        return null;
    }
}
复制代码

 

 

//

@FunctionalInterface

public interface MiddlewareNext {
    void excute();
}

 



复制代码
/**
 * 中间件管理器
 */
public class MiddlewareBuilder {
    private final List<Middleware> middlewareList;

    public MiddlewareBuilder() {
        this.middlewareList = new ArrayList<>();
    }
    
    public MiddlewareBuilder use(Middleware middleware) {
        this.middlewareList.add(middleware);
        return this;
    }
    
    public Consumer<MiddlewareContext> build(){
        MiddlewarePipeline pipeline = null;
        Collections.reverse(middlewareList);
        for (Middleware middleware : middlewareList) {
            pipeline = pipeline == null ? new MiddlewarePipeline(middleware) : pipeline.addHandler(middleware);
        }
        return pipeline::excute;
    }
    
    private static class MiddlewarePipeline {
        private final Middleware currentHandler;
        public MiddlewarePipeline(Middleware currentHandler) {
            this.currentHandler = currentHandler;
        }
        public MiddlewarePipeline addHandler(Middleware newHandler) {
            return new MiddlewarePipeline((input, next1) -> {
                MiddlewareNext next2 = () -> currentHandler.excute(input, next1);
                newHandler.excute(input, next2);
            });
        }
        public void excute(MiddlewareContext ctx){
            this.currentHandler.excute(ctx,()->{});
        }
    }
}
复制代码

 



60java

nodejsc#使

使

复制代码
//创建一个中间件构造器

MiddlewareBuilder app = new MiddlewareBuilder();

 

//添加中间件

app.use((ctx, next) -> {
    System.out.println("middle-1--->start");
    next.excute();  //进入下一个中间件
    System.out.println("middle-1--->end");
});
 

//添加中间件

app.use((ctx, next) -> {
    System.out.println("middle-2--->start");
    long startTime = System.currentTimeMillis();
    next.excute();  //进入下一个中间件
    long rt = (System.currentTimeMillis() - startTime);
    ctx.set("X-Response-Time", rt);
    System.out.println("middle-2--->end");
});
 

//添加中间件

app.use((ctx, next) -> {
    System.out.println("middle-3--->start");
    ctx.set("body", "Hello World");
    System.out.println("middle-3--->end");
});
 

//执行中间件

app.build().accept(new MiddlewareContext());
复制代码

 

 

middle-1--->start
middle-2--->start
middle-3--->start
middle-3--->end
middle-2--->end
middle-1--->end

 

springMiddleware

spring

复制代码
@Component
public class MiddlewarePointAnnotationProcessor implements BeanPostProcessor {
    private final ConfigurableListableBeanFactory configurableBeanFactory;

    @Autowired
    public MiddlewarePointAnnotationProcessor(ConfigurableListableBeanFactory beanFactory) {
        this.configurableBeanFactory = beanFactory;
    }
    
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        this.scanAnnotation(bean, beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    protected void scanAnnotation(Object bean, String beanName) {
        this.configureFieldInjection(bean);
    }

    private void configureFieldInjection(Object bean) {
        Class<?> managedBeanClass = bean.getClass();
        ReflectionUtils.FieldCallback fieldCallback =
                new MiddlewarePointFieldCallback(configurableBeanFactory, bean);
        ReflectionUtils.doWithFields(managedBeanClass, fieldCallback);
    }
}
复制代码

 



springboot使便

 


,() 

 

posted @   俞正东  阅读(813)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示