用户工具

站点工具


light4j:light-4j

light-4j.pdfOpenAPI

  • server:com.networknt.server.Server
    1. loadConfig:DefaultConfigLoader.init,通过startup从网络获取values配置(config支持inject)
    2. mergeStatusConfig:检查app-status配置,无冲突时增加到status状态码配置
    3. start:加载service单例,StartupHookProvider,加载handler或middleware
      • handler优先:继承HttpHandler或HandlerProvider,支持string、map-set字段、list-多参构造
      • middleware默认:从service获取HandlerProvider,再获取MiddlewareHandler构成处理器链
      • GracefulShutdownHandler:附加到处理器链的开头,调用server.shutdown时响应503并关停应用
    4. bind:使用Undertow.Builder配置port、https等,可选注册到registry
  • config
    1. 配置加载顺序:config,server,values,app-status,service,handler
    2. getConfigStream:-Dlight-4j-config-dir > classpath > config/,startup会下载certs、files到目录
    3. CentralizedManagement.mergeObject:ConfigInjection.getInjectValue获取values、env或default值
  • service:支持单例、多例、map-set字段、list-多参构造、多接口、泛型接口
    1. HandlerProvider:使用Handlers.routing、path等,在没有handler配置时才生效
    2. MiddlewareHandler:exceptionmetricstraceabilitycorrelationcorsopenapibodyauditsanitizer,ModuleRegistry.registerModule注册模块
  • handler:Handler.next(exchange, next)触发下一个handler
    1. initHandlers:处理handlers,支持class@name、map-set字段、list-多参构造
    2. initChains:处理chains,根据name从handlers取出实例构建处理器链
    3. initPaths:处理paths,path单方法路径、source多方法路径,使用PathTemplateMatcher匹配路径
    4. initDefaultHandlers:处理defaultHandlers,Handler.setLastHandler可选项
    5. OrchestrationHandler:匹配方法路径,否则defaultHandlers或报错,exchange.getAttachment
    1. consul
    2. zookeeper:zkclient
    3. direct:直连测试

light-4j子项目

  • audit:AuditHandler,日志器为Audit=trace,输出至target/audit.log
    • 性能影响:不启用audit > 不记录statusCode responseTime > 默认配置
    • 默认记录:timestamp=System.currentTimeMillis() serviceId⇐server.yml correlationId⇐CorrelationHandler traceabilityId⇐TraceabilityHandler clientId+userId⇐JwtVerifyHandler endpoint⇐OpenApiHandler statusCode=exchange1.getStatusCode() responseTime=System.currentTimeMillis() - start
    • audit.yml,audit:client_id+user_id+endpoint,requestBody+requestCookies+queryParameters+pathParameters,auditOnError=true时只记录statusCode>=400,logLevelIsError=true时记录error级别默认info级别
    • handler.yml,responseBody需配合auditOnError=true时才输出
  • balance:LoadBalance.select(urls,service,tag,requestKey),Cluster需要
    • RoundRobinLoadBalance,使用service|tag轮训
    • LocalFirstLoadBalance,优先URL.getHost()本机轮训,其次remote服务轮训
    • ConsistentHashLoadBalance,使用requestKey.hashCode()一致性哈希
  • basic-auth:BasicAuthHandler,处理AUTHORIZATION=BASIC {username:password}
    • basic-auth.yml,users:[{username,password}]
  • body:BodyHandler,处理application/json text/plain application/x-www-form-urlencoded multipart/form-data
    • ProxyBodyHandler,用于light-proxy http-sidecar,maxBuffers=16384,skipProxyBodyHandler=false
    • body.yml,cacheRequestBody=false缓存json串,REQUEST_BODY可能为Map<String,Object> List<Object> InputStream
  • client
    • Http2Client.getInstance(),connect连接 borrow|returnConnection池 getFormDataString正文 createClientCallback文本 byteBufferClientCallback字节 createFullCallback计时 callService请求
    • client.yml,request请求超时等,tls安全加密,oauth包含token sign deref
  • cluster,依赖balance和registry
    • LightCluster,List<URI> services(protocol, service, tag)
  • common,
    • DecryptUtil,使用Decryptor解密配置里的CRYPT:加密内容
  • config,配置优先顺序:ConfigLoader > cache > Default local(-Dlight-4j-config-dir > classpath > classpath/config)
    • Config.getInstance(),get[Default]Json(Map|Object)Config[NoCache] get(Mapper|Yaml)
    • JsonMapper,处理json
  • consul,支持向consul注册中心获取服务
  • content,设置默认Content-Type响应头
  • correlation:X-Correlation-Id,用于多个微服务之间跟踪同一个请求
  • cors:跨域处理,cors.yml
    • 有请求头Origin|Access-Control-Request-Method|Headers时,为跨域请求
    • 增加响应头Access-Control-Allow-Origin、VARY,检查Origin和getHostName()等,不匹配allowedOrigins时响应403
    • 增加响应头Access-Control-Allow-Methods=allowedMethods
    • 增加响应头Access-Control-Allow-Headers=原值或Content-Type WWW-Authenticate Authorization
    • 增加响应头Access-Control-Allow-Credentials=true Access-Control-Max-Age=60*60
    • OPTIONS响应200
  • data-source:数据源,配置com.zaxxer.hikari.HikariDataSource即可
  • decryptor:config.yml里decryptorClass=com.networknt.decrypt.[Auto|Manual]AESDecryptor
    • 密码:默认light,Auto使用环境变量light_4j_config_password,Manual从控制台输入
  • deref-token:使用client.yml的oauth.deref配置
    • 无Authorization时报错,jwt时放行,行点号.时去/oauth/deref请求jwt并通过Authorization向后传递
  • dump,生产不建议,会消费掉请求正文
  • egress-router,router.yml,路由分发请求
  • email-sender,发邮件EmailSender.sendMail[WithAttachment](to,subject,content,filename)
    • email.yml,host port user pass=默认secret.yml里emailPassword auth
  • encode-decode,处理Content-Encoding,支持deflate gzip,
  • exception,异常处理,支持(Framework|Api|Client]Exception,切工作线程,清空MDC
  • handler,业务处理
  • header,(请求|响应)头处理,支持add update
  • health,健康检查OK
  • http-entity,
    • RequestEntity.method(HttpMethod,URI,HeaderMap).body(T)
    • ResponseBuilder.status(HttpStatus),ok(body)
    • MimeType(type,subType,charset);MediaType.APPLICATION_JSON_UTF8 APPLICATION_OCTET_STREAM IMAGE_PNG
  • http-string
    • ContentType,枚举,APPLICATION_JSON APPLICATION_FORM_URLENCODED_VALUE MULTIPART_FORM_DATA_VALUE
    • HttpStringConstants,TRACEABILITY_ID=new HttpString(Constants.TRACEABILITY_ID_STRING) SERVICE_ID
  • http-url
    • HttpURL(url).getRoot(),toAbsolute encodeQueryString QueryString.addString(key,values)
  • info,响应deployment environment security component
  • ingress-proxy,proxy.yml,代理转发请求
  • ip-whitelist,
    • WhitelistHandler,whitelist.yml,defaultAllow=true,paths:{path:[127.0.0.1,10.10.*.*,127.0.0.48/30]}
  • jaeger-tracing,支持opentracing,JaegerStartupHookProvider初始化tracer,JaegerHandler上报信息
  • logger-config,logging.yml,支持获取/变更日志级别,支持获取日志内容
  • mask,mask.yml,string|regex|json={key:[pattern:replace]}
    • Mask,maskString(input,key),通过string.key获取多个[pattern:replace]依次替换input;maskJson|Regex
  • metrics,指标信息发送influxdb
  • monad-result,monad单子不可分割,Result Success Failure
  • portal-registry,向portal注册服务,PortalRegistry,portal-registry.yml
  • prometheus,指标信息通过PrometheusHandler汇总,通过PrometheusGetHandler拉取
  • rate-limit,通过RequestLimit(concurrentRequest=1000,queueSize=-1)限流,limit.yml,enabled=false
  • registry,Registry扩展了RegistryService, DiscoveryService,处理URL,DirectRegistry直连
  • resource,支持virtual-host.yml静态站,支持path-resource.yml静态页
  • sanitizer,防注入,sanitizer.yml,enabled=false
  • security,支持openapi-validator的JwtVerifyHandler校验jwt令牌,[openapi-]security.yml
  • server,server.yml
    • IConfigLoader,light-config-server-uri=config-server(DefaultConfigLoader)|nginx-git-dir(UrlConfigLoader)
    • JsonPathStartupHookProvider,使用jackson处理JsonPath.parse(json).read(“$.result.records[0].name”);
  • service,单例和依赖注入,service.yml
  • status,状态和错误码,异常定义,status.yml,code={statusCode,message,description},Status(code,args)
  • switcher,开关控制
  • traceability,MDC.tId=X-Traceability-Id
  • utility,Constants常量 StreamUtils等
light4j/light-4j.txt · 最后更改: 2021/12/01 11:33 由 admin