1 Star 0 Fork 34

傲风残月 / oxygen

forked from justlive1 / oxygen 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

oxygen

Maven Central License

轻量级Java框架

介绍

一个轻量级Java框架

  • oxygen-core

    • 配置管理,支持${attrs.key:defaultValue}表达式获取配置
    • 加解密管理,提供加解密服务内置基础加密实现,例如SHA-1、SHA-256、MD5
    • 异常管理,提供异常包装,统一异常编码,便于国际化
    • i18n国际化
    • 资源文件加载,提供file,jar,classpath等文件加载
    • 类扫描器
    • 部分工具类
    • retry重试
  • oxygen-ioc

    • 基于构造器的轻量级依赖注入
  • oxygen-aop

    • 基于cglib实现的切面
    • 轻巧简单,可单独使用
    • 可使用注解Aspect或直接实现Interceptor编写切面
  • oxygen-cache

    • 内置Ehcache和LocalCache缓存
    • 提供基于注解Cacheable的方法缓存
  • oxygen-job

    • 提供基于注解Scheduled的定时任务
  • oxygen-jdbc

    • 小巧简单的jdbc实现,纯jdk实现,无第三方jar
    • 支持多数据源
    • 基于sql进行crud,不提供类似Hibernate的链式方法(原因:sql作为数据库领域的DSL,已经很自然优雅,Less is more)
  • oxygen-web

    • 轻量级web框架支持注解声明和函数式编程
    • 支持Servlet3.0 ServletContainerInitializer 自动加载,省略web.xml
    • 支持i18n动态切换
    • 提供WebHook进行请求拦截处理
    • 支持自定义全局异常处理

特性

  • 轻量级,使用简单
  • 支持插件扩展
  • 函数式编程
  • 流式风格

快速开始

创建Maven项目

<!-- tomcat,jetty,undertow -->
<properties>
  <oxygen.server>-tomcat</oxygen.server>
</properties>

<!-- 使用内嵌容器启动 -->
<dependency>
    <groupId>vip.justlive</groupId>
    <artifactId>oxygen-web${oxygen.server}</artifactId>
    <version>${oxygen.version}</version>
</dependency>

Gradle

compile 'vip.justlive:oxygen-web-tomcat:$oxygenVersion'

不需要webapp项目框架,支持Servlet3.0

编写 main 函数写一个 Hello World

public static void main(String[] args) {
  Router.router().path("/").handler(ctx -> ctx.response().write("hello world"));
  Server.server().listen(8080);
}

用浏览器打开 http://localhost:8080 这样就可以看到 hello world 了!

内容详解

注册路由

硬编码方式

Router.router().path("/").handler(ctx -> ctx.response().write("hello world"));
Router.router().path("/get").method(HttpMethod.GET).handler(get);
Router.router().path("/post").method(HttpMethod.POST).handler(post);

注解方式

@Router("/book")
public class BookRouter {
  
  // 视图
  @Mapping("/")
  public ViewResult index() {
    return Result.view("/book.html");
  }
  
  // json
  @Mapping(value = "/ajax", method = {HttpMethod.POST})
  public Book find(RoutingContext ctx) {
    // ...
    return new Book();
  }
}

获取请求参数

表单参数或json请求参数

项目将json请求参数与表单参数合并,使用相同的方法或注解获取

使用RoutingContext获取

Router.router().path("/").handler(ctx -> {
  String id = ctx.request().getParam("id");
  ctx.response().write(id);
});

使用注解获取

@Mapping(value = "/ajax", method = {HttpMethod.POST})
public Book find(@Param Long id, @Param("tp") String type) {
  // ...
  return new Book();
}

restful参数

使用RoutingContext获取

Router.router().path("/{id}").handler(ctx -> {
  String id = ctx.request().getPathVariable("id");
  ctx.response().write(id);
});

使用注解获取

@Mapping(value = "/{id}", method = {HttpMethod.POST})
public void ajax(@PathParam("id") Long id) {
  // ...
}

header参数

使用RoutingContext获取

Router.router().path("/").handler(ctx -> {
  String id = ctx.request().getHeader("id");
  ctx.response().write(id);
});

使用注解获取

@Mapping(value = "/", method = {HttpMethod.POST})
public void ajax(@HeaderParam("id") Long id) {
  // ...
}

cookie参数

使用RoutingContext获取

Router.router().path("/").handler(ctx -> {
  String id = ctx.request().getCookie("id");
  ctx.response().write(id);
});

使用注解获取

@Mapping(value = "/", method = {HttpMethod.POST})
public void ajax(@CookieParam("id") Long id) {
  // ...
}

参数转对象

实体类

@Data
public class Book {
  private String name;
  private String author;
}

使用RoutingContext转换

Router.router().path("/").handler(ctx -> {
  // 表单或json请求参数绑定
  Book book = ctx.bindParam(Book.class);
  // cookie参数绑定
  book = ctx.bindCookie(Book.class);
  // header参数绑定
  book = ctx.bindHeader(Book.class);
  // restful参数绑定
  book = ctx.bindPathVariables(Book.class);
});

使用注解获取

@Mapping(value = "/", method = {HttpMethod.POST})
public void ajax(@Param Book b1, @CookieParam Book b2, @HeaderParam Book b3, @PathParam Book b4) {
  // ...
}

静态资源

内置默认将classpath/public,/static作为静态资源目录,支持webjars,映射到/public

自定义静态资源可使用下面代码

Router.staticRoute().prefix("/lib").location("classpath:lib");

也可以通过配置文件指定

web.static.prefix=/public
web.static.path=/public,/static,classpath:/META-INF/resources/webjars

上传文件

使用RoutingContext获取

Router.router().path("/").handler(ctx -> {
  MultipartItem file = ctx.request().getMultipartItem("file");
  // ...
});

使用注解获取

@Mapping("/")
public void upload(MultipartItem image, @MultipartParam("file1") MultipartItem file) {
  // 不使用注解则使用方法参数名作为请求参数名称
  // 使用注解指定请求参数名称
}

结果渲染

渲染json

// 使用RoutingContext返回
Router.router().path("/").handler(ctx -> {
  ctx.response().json(new Book("Java", "xxx"));
});

// 注解式
@Mapping("/")
public Book find() {
  // 直接返回对象,框架默认处理成json
  return new Book("Java", "xxx");
}

渲染文本

// 使用RoutingContext返回
Router.router().path("/").handler(ctx -> {
  ctx.response().text("hello world");
});

渲染html

// 使用RoutingContext返回
Router.router().path("/").handler(ctx -> {
  ctx.response().html("<html><body><span>hello world</span></body></html>");
});

渲染模板

内置支持了jspthymeleaf模板,默认对应resources下的WEB-INFtemplates目录

# 可通过下面配置进行更改模板目录
web.view.jsp.prefix=WEB-INF
web.view.thymeleaf.prefix=/templates

模板使用

// 使用RoutingContext
Router.router().path("/").handler(ctx -> {
  ctx.response().template("index.html");
});

Router.router().path("/").handler(ctx -> {
  Map<String, Object> attrs = new HashMap<>();
  // ...
  ctx.response().template("index.html", attrs);
});

// 注解式
@Mapping("/")
public Result index() {
  return Result.view("index.html");
}

@Mapping("/")
public Result index() {
  Map<String, Object> attrs = new HashMap<>();
  // ...
  return Result.view("index.html").addAttributes(attrs);
}

重定向

Router.router().path("/").handler(ctx -> {
  ctx.response().redirect("https://github.com/justlive1");
});

@Mapping("/a")
public Result index() {
  // 内部地址 相对于根目录: /b
  // return Result.redirect("/b"); 
  // 内部地址 相对于当前路径: /a/b
  // return Result.redirect("b");
  // 协议地址
  return Result.redirect("https://github.com/justlive1");
}

写入cookie

@Mapping("/")
public void index(RoutingContext ctx) {
  ctx.response().setCookie("hello", "world");
  ctx.response().setCookie("java", "script", 100);
  ctx.response().setCookie("uid", "xxx", ".justlive.vip", "/", 3600, true);
}

添加header

@Mapping("/")
public void index(RoutingContext ctx) {
  ctx.response().setHeader("hello", "world");
}

写入session

@Mapping("/")
public void index(RoutingContext ctx) {
  ctx.request().getSession().put("key", "value");
}

拦截器

WebHook是拦截器接口,可以实现执行前、执行后和结束拦截处理

@Slf4j
@Bean
public class LogWebHook implements WebHook {
  @Override
  public boolean before(RoutingContext ctx) {
    log.info("before");
    return true;
  }
  @Override
  public void after(RoutingContext ctx) {
    log.info("after");
  }
  @Override
  public void finished(RoutingContext ctx) {
    log.info("finished");
  }
}

异常处理

框架默认提供了一个异常处理器,如需自定义处理异常,可以像下面这样使用

@Bean
public class CustomExceptionHandler extends ExceptionHandlerImpl {

  @Override
  public void handle(RoutingContext ctx, Exception e, int status) {
    if (e instanceof CustomException) {
      // do something
    } else {
      super.handle(ctx, e, status);
    }
  }
}

部署项目

修改端口

编码指定

Server.server().listen(8080);

配置文件

server.port=8081

启动命令

java -jar -Dserver.port=8090 app.jar

运行项目

使用内嵌容器启动

启动类

public class Application {
  public static void main(String[] args) {
    Server.server().listen();
  }
}

通用打包方式

  • ${mainClass}为上面的启动类
  • 会生成lib目录存放依赖jar
<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <configuration>
        <source>${maven.compiler.source}</source>
        <target>${maven.compiler.target}</target>
        <encoding>UTF-8</encoding>
      </configuration>
    </plugin>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <configuration>
        <archive>
          <manifest>
            <addClasspath>true</addClasspath>
            <classpathPrefix>lib/</classpathPrefix>
            <mainClass>${mainClass}</mainClass>
          </manifest>
        </archive>
      </configuration>
    </plugin>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-dependency-plugin</artifactId>
      <executions>
        <execution>
          <id>copy</id>
          <phase>package</phase>
          <goals>
            <goal>copy-dependencies</goal>
          </goals>
          <configuration>
            <outputDirectory>${project.build.directory}/lib</outputDirectory>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

打成fat-jar:

  • 使用springboot打包插件
<build>
  <plugins>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
      <version>1.3.8.RELEASE</version>
      <executions>
        <execution>
          <phase>package</phase>
          <goals>
            <goal>repackage</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

使用外部容器(jetty、tomcat等)

无需web.xml配置,打包成war放入容器即可,实现机制可查看WebContainerInitializer

<!-- 解决默认打war包报错 webxml attribute is required -->
<properties>
  <failOnMissingWebXml>false</failOnMissingWebXml>
</properties>

外部化配置

框架可以通过使用配置文件进行修改默认属性

##### 基础配置
# 配置覆盖地址,用户外部配置覆盖项目配置 例 file:/config/*.properties,classpath*:/config/*.properties,xx.properties
config.override.path=
# 类扫描路径属性
main.class.scan=vip.justlive
# 临时文件根目录
main.temp.dir=.oxygen
# 缓存实现类,自定义缓存时使用
cache.impl.class=


##### web 
# embedded 启动端口
server.port=8080
# context path
server.contextPath=
# session失效时间,单位秒
web.session.expired=3600
# 默认静态资源请求前缀
web.static.prefix=/public
# 默认静态资源目录
web.static.path=/public,/static,classpath:/META-INF/resources/webjars
# 静态资源缓存时间
web.static.cache=3600
# jsp路径前缀
web.view.jsp.prefix=WEB-INF
# thymeleaf 路径前缀
web.view.thymeleaf.prefix=/templates
# thymeleaf 视图后缀
web.view.thymeleaf.suffix=.html
# 内置简单视图处理 路径前缀
web.view.simple.prefix=/templates
# 内置简单视图处理 视图后缀
web.view.simple.suffix=.htm
# 是否开启模板缓存
web.view.cache.enabled=true


##### 定时任务job
# job线程名称格式
job.thread.name.format=jobs-%d
# job核心线程池大小
job.core.pool.size=10


##### i18n国际化
# i18n配置文件地址
i18n.path=classpath:message/*.properties
# i18n默认语言
i18n.default.language=zh
# i18n默认国家
i18n.default.country=CN
# i18n参数key
i18n.param.key=locale
# i18n Session key
i18n.session.key=I18N_SESSION_LOCALE


##### jetty
# 虚拟主机
server.jetty.virtualHosts=
# 连接器在空闲状态持续该时间后(单位毫秒)关闭
server.jetty.idleTimeout=30000
# 温和的停止一个连接器前等待的时间(毫秒)
server.jetty.stopTimeout=30000
# 等待处理的连接队列大小
server.jetty.acceptQueueSize=
# 允许Server socket被重绑定,即使在TIME_WAIT状态
server.jetty.reuseAddress=true
# 是否启用servlet3.0特性
server.jetty.configurationDiscovered=true
# 最大表单数据大小
server.jetty.maxFormContentSize=256 * 1024 * 1024
# 最大表单键值对数量
server.jetty.maxFormKeys=200


##### tomcat
# 最大请求队列数
server.tomcat.acceptCount=100
# 最大连接数
server.tomcat.maxConnections=5000
# 最大工作线程数
server.tomcat.maxThreads=200
# 最小线程数
server.tomcat.minSpareThreads=10
# 最大请求头数据大小
server.tomcat.maxHttpHeaderSize=8 * 1024
# 最大表单数据大小
server.tomcat.maxHttpPostSize=2 * 1024 * 1024
# 连接超时
server.tomcat.connectionTimeout=20000
# URI解码编码
server.tomcat.uriEncoding=utf-8
# 调用backgroundProcess延迟时间
server.tomcat.backgroundProcessorDelay=10
# 是否启用访问日志
server.tomcat.accessLogEnabled=false
# 访问日志是否开启缓冲
server.tomcat.accessLogBuffered=true
# 是否设置请求属性,ip、host、protocol、port
server.tomcat.accessLogRequestAttributesEnabled=false
# 每日日志格式
server.tomcat.accessLogFileFormat=.yyyy-MM-dd
# 日志格式
server.tomcat.accessLogPattern=common



##### undertow
# 主机名
server.undertow.host=0.0.0.0
# io线程数
server.undertow.ioThreads=
# worker线程数
server.undertow.workerThreads=
# 是否开启gzip压缩
server.undertow.gzipEnabled=false
# gzip处理优先级
server.undertow.gzipPriority=100
# 压缩级别,默认值 -1。 可配置 1 到 9。 1 拥有最快压缩速度,9 拥有最高压缩率
server.undertow.gzipLevel=-1
# 触发压缩的最小内容长度
server.undertow.gzipMinLength=1024
# url是否允许特殊字符
server.undertow.allowUnescapedCharactersInUrl=true
# 是否开启http2
server.undertow.http2enabled=false

联系信息

E-mail: qq11419041@163.com

QQ群: 950216299

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2018 justlive1 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

一个轻量级Java框架,包含ioc、aop、config、cache、job、Jdbc、web等 展开 收起
Java
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Java
1
https://gitee.com/aofengcanyue/oxygen.git
git@gitee.com:aofengcanyue/oxygen.git
aofengcanyue
oxygen
oxygen
master

搜索帮助