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 @ 2021-04-18 22:01  俞正东  阅读(634)  评论(0编辑  收藏  举报