当前位置: 首页 > 软件库 > Web应用开发 > Web框架 >

Resty

极简的RESTful框架(服务端+客户端)
授权协议 Apache
开发语言 Java
所属分类 Web应用开发、 Web框架
软件类型 开源软件
地区 国产
投 递 者 酆阳煦
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

源码链接:OSC -> Resty   Github -> Resty   在线开发手册

如果你还不是很了解restful,或者认为restful只是一种规范不具有实际意义,推荐一篇osc两年前的文章:RESTful API 设计最佳实践  和 Infoq的一篇极其理论的文章  理解本真的REST架构风格 虽然有点老,介绍的也很简单,大家权当了解,restful的更多好处,还请google

拥有jfinal/activejdbc一样的activerecord的简洁设计,使用更简单的restful框架

部分设计也来自jfinal+activejdbc+restx,也希望大家多多支持开源,开源不比较框架之间的优劣,只描述自己的想法。

restful的api设计,是作为restful的服务端最佳选择(使用场景:客户端和服务端解藕,用于对静态的html客户端(mvvm等),ios,andriod等提供服务端的api接口)

下载jar包: Resty jar

maven使用方式:
1. 添加maven snapshots仓库

<repositories>
    <repository>
      <id>oss-snapshots</id>
      <url>https://oss.sonatype.org/content/repositories/snapshots</url>
      <releases>
        <enabled>false</enabled>
      </releases>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>
  </repositories>

2. 添加依赖包

<dependency>
    <groupId>cn.dreampie</groupId>
    <artifactId>resty-route</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

重大更新:

Record的时代已经到来,你完全不用使用任何的model来执行你的数据 

//创建record的执行器  针对sec_user表 并开启缓存
Record recordDAO = new Record("sec_user",true);
//使用当前数据源和表数据 new一个对象来保存数据
recordDAO.reNew().set("属性", "值").save();
Record r1 = recordDAO.reNew().set("属性", "值");
Record r2 = recordDAO.reNew().set("属性", "值");
//批量保存
recordDAO.save(r1, r2);
//更新
r2.set("属性", "值").update()
//查询全部
List<Record> records = recordDAO.findAll();
//条件查询
recordDAO.findBy(where,paras)
//分页查询
Page<Record> records = recordDAO.paginateAll();
//根据id删除
recordDAO.deleteById("1");

//本次查询放弃使用cache 
recordDAO.unCache().findBy(where,paras);
//把record的数据源切换到dsName数据源上
recordDAO.useDS(dsName).findBy(where,paras);

//等等,完全摆脱model,实现快速操作数据

//Model支持动态切换数据源和本次查询放弃使用cache

User dao=new User();
//本次查询放弃使用cache 
dao.unCache().findBy(where,paras);
//把model的数据源切换到dsName数据源上
dao.useDS(dsName).findBy(where,paras);

//数据库和全局参数配置移植到application.properties  详情参看resty-example

//not must auto load
app.encoding=UTF-8
app.devMode=true
app.showRoute=true
app.cacheEnabled=true


//druid plugin auto load
//dsName is "default"  you can use everything
db.default.url=jdbc:mysql://127.0.0.1/example?useUnicode=true&characterEncoding=UTF-8
db.default.user=dev
db.default.password=dev1010
db.default.dialect=mysql
druid.default.initialSize=10
druid.default.maxPoolPreparedStatementPerConnectionSize=20
druid.default.timeBetweenConnectErrorMillis=1000
druid.default.filters=slf4j,stat,wall

//flyway database migration auto load
flyway.default.valid.clean=true
flyway.default.migration.auto=true
flyway.default.migration.initOnMigrate=true


//数据库的配置精简  自动从文件读取参数  只需配置model扫描目录 和dsName
public void configPlugin(PluginLoader pluginLoader) {
  //第一个数据库
  ActiveRecordPlugin activeRecordPlugin = new ActiveRecordPlugin(new DruidDataSourceProvider("default"), true);
  activeRecordPlugin.addIncludePaths("cn.dreampie.resource");
  pluginLoader.add(activeRecordPlugin);
}

一、独有优点:

1.极简的route设计:

@GET("/users/:name")  //在路径中自定义解析的参数 如果有其他符合 也可以用 /users/{name}
// 参数名就是方法变量名  除路径参数之外的参数也可以放在方法参数里  传递方式 user={json字符串}
public Map find(String name,User user) {
  // return Lister.of(name);
  return Maper.of("k1", "v1,name:" + name, "k2", "v2");//返回什么数据直接return,完全融入普通方法的方式
}

2.极简的activerecord设计,数据操作只需短短的一行 ,支持批量保存对象

//批量保存
User u1 = new User().set("username", "test").set("providername", "test").set("password", "123456");
User u2 = new User().set("username", "test").set("providername", "test").set("password", "123456");
User.dao.save(u1,u2);

//普通保存
User u = new User().set("username", "test").set("providername", "test").set("password", "123456");
u.save();

//更新
u.update();
//条件更新
User.dao.updateBy(columns,where,paras);
User.dao.updateAll(columns,paras);

//删除
u.deleted();
//条件删除
User.dao.deleteBy(where,paras);
User.dao.deleteAll();

//查询
User.dao.findById(id);
User.dao.findBy(where,paras);
User.dao.findAll();

//分页
User.dao.paginateBy(pageNumber,pageSize,where,paras);
User.dao.paginateAll(pageNumber,pageSize);

3.极简的客户端设计,支持各种请求,文件上传和文件下载(支持断点续传)

Client client=null;//创建客户端对象
//启动resty-example项目,即可测试客户端
String apiUrl = "http://localhost:8081/api/v1.0";
//如果不需要 使用账号登陆
//client = new Client(apiUrl);
//如果有账号权限限制  需要登陆
client = new Client(apiUrl, "/tests/login", "u", "123");

//该请求必须  登陆之后才能访问  未登录时返回 401  未认证
ClientRequest authRequest = new ClientRequest("/users", HttpMethod.GET);
ResponseData authResult = client.build(authRequest).ask();
System.out.println(authResult.getData());

//get
ClientRequest getRequest = new ClientRequest("/tests", HttpMethod.GET);
ResponseData getResult = client.build(getRequest).ask();
System.out.println(getResult.getData());

//post
ClientRequest postRequest = new ClientRequest("/tests", HttpMethod.POST);
postRequest.addParameter("test", Jsoner.toJSONString(Maper.of("a", "谔谔")));
ResponseData postResult = client.build(postRequest).ask();
System.out.println(postResult.getData());

//put
ClientRequest putRequest = new ClientRequest("/tests/x", HttpMethod.PUT);
ResponseData putResult = client.build(putRequest).ask();
System.out.println(putResult.getData());


//delete
ClientRequest deleteRequest = new ClientRequest("/tests/a", HttpMethod.DELETE);
ResponseData deleteResult = client.build(deleteRequest).ask();
System.out.println(deleteResult.getData());


//upload
ClientRequest uploadRequest = new ClientRequest("/tests/resty", HttpMethod.POST);
uploadRequest.addUploadFiles("resty", ClientTest.class.getResource("/resty.jar").getFile());
uploadRequest.addParameter("des", "test file  paras  测试笔");
ResponseData uploadResult = client.build(uploadRequest).ask();
System.out.println(uploadResult.getData());


//download  支持断点续传
ClientRequest downloadRequest = new ClientRequest("/tests/file", HttpMethod.GET);
downloadRequest.setDownloadFile(ClientTest.class.getResource("/resty.jar").getFile().replace(".jar", "x.jar"));
ResponseData downloadResult = client.build(downloadRequest).ask();
System.out.println(downloadResult.getData());

4.支持多数据源和嵌套事务(使用场景:需要访问多个数据库的应用,或者作为公司内部的数据中间件向客户端提供数据访问api等)

// 在resource里使用事务,也就是controller里,rest的世界认为所以的请求都表示资源,所以这儿叫resource
@GET("/users")
@Transaction(name = {DS.DEFAULT_DS_NAME, "demo"}) //多数据源的事务,如果你只有一个数据库  直接@Transaction 不需要参数
public User transaction() {
//TODO 用model执行数据库的操作  只要有操作抛出异常  两个数据源 都会回滚  虽然不是分布式事务  也能保证代码块的数据执行安全
}

// 如果你需要在service里实现事务,通过java动态代理(必须使用接口,jdk设计就是这样)
public interface UserService {
  @Transaction(name = {DS.DEFAULT_DS_NAME, "demo"})//service里添加多数据源的事务,如果你只有一个数据库  直接@Transaction 不需要参数
  public User save(User u);
}
// 在resource里使用service层的 事务
// @Transaction(name = {DS.DEFAULT_DS_NAME, "demo"})的注解需要写在service的接口上
// 注意java的自动代理必须存在接口
// TransactionAspect 是事务切面 ,你也可以实现自己的切面比如日志的Aspect,实现Aspect接口
// 再private UserService userService = AspectFactory.newInstance(new UserServiceImpl(), new TransactionAspect(),new LogAspect());
private UserService userService = AspectFactory.newInstance(new UserServiceImpl(), new TransactionAspect());

5.极简的权限设计,你只需要实现一个简单接口和添加一个拦截器,即可实现基于url的权限设计

public void configInterceptor(InterceptorLoader interceptorLoader) {  //权限拦截器 放在第一位 第一时间判断 避免执行不必要的代码
  interceptorLoader.add(new SecurityInterceptor(new MyAuthenticateService()));
}
//实现接口
public class MyAuthenticateService implements AuthenticateService {  
//登陆时 通过name获取用户的密码和权限信息
  public Principal findByName(String name) {
    DefaultPasswordService defaultPasswordService = new DefaultPasswordService();

    Principal principal = new Principal(name, defaultPasswordService.hash("123"), new HashSet<String>() {{
      add("api");
    }});    
    return principal;
  }  
  //基础的权限总表  所以的url权限都放在这儿  你可以通过 文件或者数据库或者直接代码 来设置所有权限
  public Set<Credential> loadAllCredentials() {
      Set<Credential> credentials = new HashSet<Credential>();
      credentials.add(new Credential("GET", "/api/v1.0/users**", "users"));
      return credentials;
  }
}

6.极简的缓存设计,可扩展,非常简单即可启用model的自动缓存功能

public void configConstant(ConstantLoader constantLoader) {
  //启用缓存并在要自动使用缓存的model上  开启缓存@Table(name = "sec_user", cached = true)
  constantLoader.setCacheEnable(true);
}

@Table(name = "sec_user", cached = true)
public class User extends Model<User> {
  public static User dao = new User();

}

7.下载文件,只需要直接return file

@GET("/files")
public File file() {
  return new File(path);
}

8.上传文件,通过@FILE注解件写到服务器

@POST("/files")
@FILE(dir = "/upload/") //配置上传文件的相关信息
public UploadedFile file(UploadedFile file) {    
  return file;
}

9.当然也是支持传统的web开发,你可以自己实现数据解析,在config里添加自定义的解析模板

public void configConstant(ConstantLoader constantLoader) {
  // 通过后缀来返回不同的数据类型  你可以自定义自己的  render  如:FreemarkerRender
  // constantLoader.addRender("json", new JsonRender());
  //默认已添加json和text的支持,只需要把自定义的Render add即可
}

二、运行example示例:

1.运行根目录下的pom.xml->install (把相关的插件安装到本地,功能完善之后发布到maven就不需要这样了)

2.在本地mysql数据库里创建demo,example数据库,对应application.properties的数据库配置

3.运行resty-example下的pom.xml->flyway-maven-plugin:migration,自动根具resources下db目录下的数据库文件生成数据库表结构

4.运行resty-example下的pom.xml->tomcat7-maven-plugin:run,启动example程序

提醒:推荐idea作为开发ide,使用分模块的多module开发




  • Simple HTTP and REST client library for Go。简单理解 java里的HttpClient,用于发送http 或rest协议的请求。 github:GitHub - go-resty/resty: Simple HTTP and REST client library for Go api doc:resty package - github.com/go-r

  • 最近接触公司的openResty项目,有的时候需要本地测试一些代码,可以用resty 命令行工具,跑一些代码,防止出现空指针 比如我遇到msg=/usr/local/mzfs/src/mzis-web/xxx.lua:2739: invalid value (nil) at index 3 in table for ‘concat’」,很明显就是 concat 中出现nil 改动代码后,造了一些数

  • openresty lua-resty-lock数据库锁             官网:https://github.com/openresty/lua-resty-lock                                                                         lua-resty-lock 说明             This libra

  • openresty lua-resty-redis使用                                                                  lua-resty-redis 使用             redis:new():创建redis对象 语法格式:red, err = redis:new() Creates a redis object. I

  • openresty lua-resty-balancer动态负载均衡              lua-resty-balancer:https://github.com/openresty/lua-resty-balancer.git ngx.balancer:https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/bala

  • openresty lua-resty-dns 域名解析                  官网:https://github.com/openresty/lua-resty-dns                                                                     lua-resty-dns 使用              This libra

  • openresty lua-resty-core 使用           官网:https://github.com/openresty/lua-resty-core                                                                            lua-resty-core 使用           This library

  • openresty lua-resty-logger-socket日志传输          lua-resty-logger-socket:https://github.com/cloudflare/lua-resty-logger-socket sylog-ng:https://github.com/syslog-ng/syslog-ng                            

  • openresty lua-resty-lrucache缓存           lua-resty-lrucache:https://github.com/openresty/lua-resty-lrucache                                                                          lrucache 缓存        

 相关资料
  • 24.10 在客户端访问RESTful服务 RestTemplate是客户端访问RESTful服务的核心类。它在概念上类似于Spring中的其他模板类,例如JdbcTemplate、 JmsTemplate和其他Spring组合项目中发现的其他模板类。 RestTemplate’s behavior is customized by providing callback methods and c

  • 我是web服务编程新手,我想使用netbeans 6在Grizzly服务器上使用Jersey创建一个restful web服务,然后创建一个客户端javascript,以便通过浏览器使用该web服务。因此,我开始了解更多关于restful web服务的知识,并在网上阅读了大量指南,然后通过阅读jersey用户指南http://jersey . Java . net/nonav/documentat

  • 客户端-服务器(Client/Server)结构简称 C/S 结构,是一种网络架构,通常在该网络架构下的软件分为客户端和服务器。 服务器是整个应用系统资源的存储和管理中心,多个客户端分别各自处理相应的功能,共同实现完整的应用。在客户/服务器结构中,客户端用户的请求被传送到数据库服务器,数据库服务器进行处理后,将结果返回给用户,从而减少网络数据的传输量。 用户在使用应用程序时,首先启动客户端,然后通

  • 我想在一些计算机之间建立点对点连接,这样用户就可以在没有外部服务器的情况下聊天和交换文件。我最初的想法如下: 我在服务器上制作了一个中央服务器插座,所有应用程序都可以连接到该插座。此ServerSocket跟踪已连接的套接字(客户端),并将新连接的客户端的IP和端口提供给所有其他客户端。每个客户端都会创建一个新的ServerSocket,所有客户端都可以连接到它。 换句话说:每个客户端都有一个Se

  • 我正在使用获取对象。但是当我在客户端运行Main时出现错误,请告诉我如何修复它??? 线程“main”org.springframework.http.converter.httpMessageNotreadableException:无法读取JSON:无法将edu.java.spring.service.user.model.user实例反序列化出START_ARRAY令牌[source:sun

  • 我有一个包含10个微服务的微服务架构,每个微服务提供一个客户端。在由微服务团队管理/控制的客户机内部,我们只接收参数并将它们传递给一个通用http调用程序,该调用程序接收endpoint和N个params,然后进行调用。所有微服务都使用http和web api(我猜技术并不重要)。 对于我来说,作为微服务团队提供一个客户是没有意义的,应该是消费者的责任,如果他们想创建一些抽象或者直接调用它是他们的

  • 问题内容: 我有stfw,但是找不到在Java中创建Web服务客户端的简单/独立方法。 有人在此链接/示例吗? 问题答案: 使用Axis2怎么样? 只需按照快速入门指南进行操作,就可以轻松应对。 这是另一个更具描述性的指南

  • Lazy 微服务客户端 Sometimes you have to load initial data before you can create your @Client(). In this case, you can use ClientProxyFactory, which provides create() method. 有时候在创建@Client()之前你需要加载原始数据。这时,你可