响应式Filter和普通Filter处理前后端

一、响应式Filter

1.初始化

Map<String,Object> urlMap=new HashMap<>();
@PostConstruct
public void init(){
    BufferedReader br=null;
    try {

         br= new BufferedReader(new InputStreamReader(AuthFilter.class.getResourceAsStream("/interface.json"), StandardCharsets.UTF_8));
        StringBuffer sb = new StringBuffer();
        String tmp = null;
        while ((tmp = br.readLine()) != null) {
            sb.append(tmp);
        }
        ArrayList<MethodOperationDTO> dtos=new Gson().fromJson(sb.toString(),new TypeToken<ArrayList<MethodOperationDTO>>(){}.getType());
        for(MethodOperationDTO mo:dtos){
            Object sysObj=urlMap.get(mo.getSystem());
            if(sysObj==null) {
                sysObj=new HashMap<String,Object>();
                urlMap.put(mo.getSystem(),sysObj);
            }
            putLoopMap((Map<String,Object>)sysObj,mo.getUrl(),mo.getMethod(),mo.getOperName());
        }
        log.info("urlMap size:{}",urlMap.size());
        //System.out.println(urlMap);
    }catch(Exception e){
        log.error(e.getMessage(),e);
    }finally{
        if(br!=null){
            try {
                br.close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }
    }
}

其中的把URL放入Map的方法,和根据URL获取操作的方法

public void putLoopMap(Map<String,Object> sysMap,String url,String method,String name){
    if(url.startsWith("/")){
        url=url.replaceFirst("/","");
    }
    String urlSplit[]=url.split("/");
    Map<String,Object> curMap=sysMap;
    Map<String,Object> nextMap=null;

    for(int i=0;i<urlSplit.length;i++){
        nextMap=(Map<String,Object>)curMap.get(urlSplit[i]);
        if(nextMap==null){
            nextMap=new HashMap<>();
        }
        curMap.put(urlSplit[i],nextMap);
        curMap=nextMap;
    }
    if(nextMap==null){
        nextMap=new HashMap<>();
    }

    nextMap.put(method,name);
}

public String getName(String url,String method){
    if(url.startsWith("/")){
        url=url.replaceFirst("/","");
    }
    String urlSplit[]=url.split("/");
    Map<String,Object> nextMap=urlMap;
    for(int i=0;i<urlSplit.length;i++){
        Map<String,Object> map=(Map<String,Object>)nextMap.get(urlSplit[i]);
        if(map!=null){
            nextMap=map;
        }else{
            return "";
        }
    }
    if(nextMap!=null&&method!=null){
        Object obj=nextMap.get(method.toUpperCase());
        if(obj!=null && obj instanceof  String){
            String name= String.valueOf(obj);
            if(name.length()>100){
                name=name.substring(0,100);
            }
            return name;
        }
    }
    return "";
}



2.filter设置Response

public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
 	SystemLog systemLog =new SystemLog();
 	ServerHttpResponseDecorator response=getResponseStatusMsg(exchange,systemLog);
  	return chain.filter(exchange.mutate().request(requestDecorator).response(response).build()).then();
}


public ServerHttpResponseDecorator getResponseStatusMsg(ServerWebExchange exchange,SystemLog systemLog){
    ServerHttpResponse originalResponse = exchange.getResponse();
    ServerHttpResponseDecorator response = new ServerHttpResponseDecorator(originalResponse) {
        @Override
        public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
            if (HttpStatus.OK.equals(getStatusCode())){
                systemLog.setStatus(BusinessStatus.SUCCESS.ordinal());
            }else{
                systemLog.setStatus(BusinessStatus.FAIL.ordinal());
            }
            systemLog.setOperationName(getName(systemLog.getOperation(),systemLog.getMethod()));

            logService.updateById(systemLog);
            /*
            //如返回的是json,要解析json内容,可以用如下方法
            if (body instanceof Flux) {
                DataBufferFactory bufferFactory = originalResponse.bufferFactory();
                Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                return super.writeWith(fluxBody.buffer().map(dataBuffers -> {

                    DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                    DataBuffer dataBuffer = dataBufferFactory.join(dataBuffers);
                    byte[] content = new byte[dataBuffer.readableByteCount()];
                    dataBuffer.read(content);
                    // 乱码
                    String s = new String(content, Charsets.UTF_8);
                    try {
                        //如果返回的是正常码,但结构体是异常的,记录失败
                        if (HttpStatus.OK.equals(getStatusCode())){
                            BaseResult rst=new Gson().fromJson(s, new com.google.common.reflect.TypeToken<BaseResult>(){}.getType());
                            if(!"200".equals(rst.getStatus())){
                                systemLog.setStatus(BusinessStatus.FAIL.ordinal());
                            }
                        }
                    }catch(Exception e){
                    }
                    DataBufferUtils.release(dataBuffer);
                    logService.updateById(systemLog);
                    return bufferFactory.wrap(content);
                }));
            }

             */

            return super.writeWith(body);
        }

        @Override
        public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) {
            return writeWith(Flux.from(body).flatMapSequential(p -> p));
        }
    };
    return response;
}

文/程忠 浏览次数:0次   2023-09-21 09:39:58

相关阅读


评论:
点击刷新

↓ 广告开始-头部带绿为生活 ↓
↑ 广告结束-尾部支持多点击 ↑