Resty開(kāi)發(fā)restful版本的Jfinal深入研究
前言
自發(fā)現(xiàn)了resty后,一直進(jìn)行深入考究到深夜3點(diǎn)才睡,只想說(shuō)這6個(gè)小時(shí)的體驗(yàn)博主內(nèi)心是滿足的!說(shuō)resty是restful版的Jfinal之Resty,其實(shí)有點(diǎn)過(guò)了,只是大部分人知道Jfinal,不一定知道還有個(gè)resty,resty的框架設(shè)計(jì)大量借鑒了Jfinal極簡(jiǎn)開(kāi)發(fā)的思想,先拋開(kāi)resty是否有重復(fù)造輪子之嫌!就作者寫(xiě)了大量的Jfinal插件后,提煉出針對(duì)restful開(kāi)發(fā)的resty來(lái),我覺(jué)得還是有意義的。而且,正好博主近期在開(kāi)發(fā)一個(gè)app的一個(gè)項(xiàng)目,需要寫(xiě)接口給客戶端調(diào)用,對(duì)比下來(lái)發(fā)現(xiàn)resty針對(duì)這個(gè)事情幫你想好了很多東西。對(duì)于接觸過(guò)Jfinal的朋友來(lái)說(shuō),使用resty開(kāi)發(fā)是件so easy的事情, 下面是官方實(shí)例,大家感受下
作者的Jfinal插件地址:https://github.com/Dreampie/jfinal-dreampie
resty開(kāi)發(fā)文檔:https://dreampie.gitbooks.io/
官方實(shí)例
maven使用方式:
1.添加依賴包
<dependency>
<groupId>cn.dreampiegroupId>
<artifactId>resty-routeartifactId>
<version>1.0version>
<dependency>2.如果使用帶有-SNAPSHOT后綴的包,請(qǐng)?zhí)砑釉搨}(cāng)庫(kù)
<repositories>
<repository>
<id>oss-snapshotsid>
<url>https://oss.sonatype.org/content/repositories/snapshotsurl>
<releases>
<enabled>trueenabled>
releases>
<snapshots>
<enabled>trueenabled>
snapshots>
repository>
<repositories>一、獨(dú)有優(yōu)點(diǎn):
重大更新:
1.2.0更新內(nèi)容:使用header來(lái)控制api版本,基于數(shù)據(jù)源的讀寫(xiě)分離,更簡(jiǎn)單的tableSetting.詳情查看
1.1.0版本重大更新:快速接入spring,緩存,加密,header,XForwardedSupports等,詳情查看
Record的時(shí)代已經(jīng)到來(lái),你完全不用使用任何的model來(lái)執(zhí)行你的數(shù)據(jù)
//創(chuàng)建record的執(zhí)行器 針對(duì)sec_user表 并開(kāi)啟緩存
Record recordDAO = new Record("sec_user");
//使用當(dāng)前數(shù)據(jù)源和表數(shù)據(jù) new一個(gè)對(duì)象來(lái)保存數(shù)據(jù)
recordDAO.reNew().set("屬性", "值").save();
Record r1 = recordDAO.reNew().set("屬性", "值");
Record r2 = recordDAO.reNew().set("屬性", "值");
//批量保存
recordDAO.save(r1, r2);
//更新
r2.set("屬性", "值").update()
//查詢?nèi)?
List<Record> records = recordDAO.findAll();
//條件查詢
recordDAO.findBy(where,paras)
//分頁(yè)查詢
Page<Record> records = recordDAO.paginateAll();
//根據(jù)id刪除 recordDAO.deleteById("1");
//本次查詢放棄使用
cache recordDAO.unCache().findBy(where,paras);
//把record的數(shù)據(jù)源切換到dsmName數(shù)據(jù)源上
recordDAO.useDS(dsmName).findBy(where,paras);
//等等,完全擺脫model,實(shí)現(xiàn)快速操作數(shù)據(jù) Model支持動(dòng)態(tài)切換數(shù)據(jù)源和本次查詢放棄使用cache
User dao=new User(); //本次查詢放棄使用cache dao.unCache().findBy(where,paras); //把model的數(shù)據(jù)源切換到dsmName數(shù)據(jù)源上 dao.useDS(dsmName).findBy(where,paras);
//數(shù)據(jù)庫(kù)和全局參數(shù)配置移植到application.properties 詳情參看resty-example
#not must auto load
app.encoding=UTF-8 app.devMode=true app.showRoute=false app.cacheEnabled=true #默認(rèn)使用ehcacheProvider
#app.cacheProvider=cn.dreampie.cache.redis.RedisProvider ##druid plugin auto load
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
#c3p0配置
c3p0.default.minPoolSize=3 c3p0.default.maxPoolSize=20 #druid配置
#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 db.demo.url=jdbc:mysql://127.0.0.1/demo?useUnicode=true&characterEncoding=UTF-8 db.demo.user=dev
db.demo.password=dev1010
db.demo.dialect=mysql
#druid
druid.demo.initialSize=10 druid.demo.maxPoolPreparedStatementPerConnectionSize=20 druid.demo.timeBetweenConnectErrorMillis=1000 druid.demo.filters=slf4j,stat,wall
#flyway
flyway.demo.valid.clean=true flyway.demo.migration.auto=true flyway.demo.migration.initOnMigrate=true //數(shù)據(jù)庫(kù)的配置精簡(jiǎn) 自動(dòng)從文件讀取參數(shù) 只需配置model掃描目錄 和dsmName public void configPlugin(PluginLoader pluginLoader) { //第一個(gè)數(shù)據(jù)庫(kù) ActiveRecordPlugin activeRecordPlugin = new ActiveRecordPlugin(new DruidDataSourceProvider("default"), true);
activeRecordPlugin.addIncludePaths("cn.dreampie.resource");
pluginLoader.add(activeRecordPlugin);
}1.極簡(jiǎn)的route設(shè)計(jì),完全融入普通方法的方式,方法參數(shù)就是請(qǐng)求參數(shù),方法返回值就是數(shù)據(jù)返回值
@GET("/users/:name")
//在路徑中自定義解析的參數(shù) 如果有其他符合 也可以用 /users/{name}
// 參數(shù)名就是方法變量名 除路徑參數(shù)之外的參數(shù)也可以放在方法參數(shù)里 傳遞方式
user={json字符串} public Map find(String name,User user) {
// return Lister.of(name);
return Maper.of("k1", "v1,name:" + name, "k2", "v2");
//返回什么數(shù)據(jù)直接return }2.極簡(jiǎn)的activerecord設(shè)計(jì),數(shù)據(jù)操作只需短短的一行,支持批量保存對(duì)象
//批量保存
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();
//分頁(yè)
User.dao.paginateBy(pageNumber,pageSize,where,paras);
User.dao.paginateAll(pageNumber,pageSize);3.極簡(jiǎn)的客戶端設(shè)計(jì),支持各種請(qǐng)求,文件上傳和文件下載(支持?jǐn)帱c(diǎn)續(xù)傳)
Client client=null;
//創(chuàng)建客戶端對(duì)象
//啟動(dòng)resty-example項(xiàng)目,即可測(cè)試客戶端
String apiUrl = "http://localhost:8081/api/v1.0";
//如果不需要 使用賬號(hào)登陸
//client = new Client(apiUrl);
//如果有賬號(hào)權(quán)限限制 需要登陸
client = new Client(apiUrl, "/tests/login", "u", "123");
//該請(qǐng)求必須 登陸之后才能訪問(wèn) 未登錄時(shí)返回 401 未認(rèn)證
ClientRequest authRequest = new ClientRequest("/users");
ClientResult authResult = client.build(authRequest).get();
System.out.println(authResult.getResult());
//get ClientRequest getRequest = new ClientRequest("/tests");
ClientResult getResult = client.build(getRequest).get();
System.out.println(getResult.getResult());
//post ClientRequest postRequest = new ClientRequest("/tests");
postRequest.addParam("test", Jsoner.toJSONString(Maper.of("a", "諤諤")));
ClientResult postResult = client.build(postRequest).post();
System.out.println(postResult.getResult());
//put ClientRequest putRequest = new ClientRequest("/tests/x");
ClientResult putResult = client.build(putRequest).put();
System.out.println(putResult.getResult());
//delete ClientRequest deleteRequest = new ClientRequest("/tests/a");
ClientResult deleteResult = client.build(deleteRequest).delete();
System.out.println(deleteResult.getResult());
//upload ClientRequest uploadRequest = new ClientRequest("/tests/resty");
uploadRequest.addUploadFiles("resty", ClientTest.class.getResource("/resty.jar").getFile());
uploadRequest.addParam("des", "test file paras 測(cè)試筆");
ClientResult uploadResult = client.build(uploadRequest).post();
System.out.println(uploadResult.getResult());
//download 支持?jǐn)帱c(diǎn)續(xù)傳
ClientRequest downloadRequest = new ClientRequest("/tests/file");
downloadRequest.setDownloadFile(ClientTest.class.getResource("/resty.jar").getFile().replace(".jar", "x.jar"));
ClientResult downloadResult = client.build(downloadRequest).get();
System.out.println(downloadResult.getResult());4.支持多數(shù)據(jù)源和嵌套事務(wù)(使用場(chǎng)景:需要訪問(wèn)多個(gè)數(shù)據(jù)庫(kù)的應(yīng)用,或者作為公司內(nèi)部的數(shù)據(jù)中間件向客戶端提供數(shù)據(jù)訪問(wèn)api等)
// 在resource里使用事務(wù),也就是controller里,rest的世界認(rèn)為所以的請(qǐng)求都表示資源,所以這兒叫
resource @GET("/users")
@Transaction(name = {"default", "demo"})
//多數(shù)據(jù)源的事務(wù),如果你只有一個(gè)數(shù)據(jù)庫(kù) 直接
@Transaction 不需要參數(shù) public User transaction() {
//TODO 用model執(zhí)行數(shù)據(jù)庫(kù)的操作 只要有操作拋出異常 兩個(gè)數(shù)據(jù)源 都會(huì)回滾 雖然不是分布式事務(wù) 也能保證代碼塊的數(shù)據(jù)執(zhí)行安全}
// 如果你需要在service里實(shí)現(xiàn)事務(wù),通過(guò)java動(dòng)態(tài)代理(必須使用接口,jdk設(shè)計(jì)就是這樣)
public interface UserService { @Transaction(name = {"demo"})
//service里添加多數(shù)據(jù)源的事務(wù),如果你只有一個(gè)數(shù)據(jù)庫(kù) 直接@Transaction 不需要參數(shù) public User save(User u);}
// 在resource里使用service層的 事務(wù)
// @Transaction(name = {"demo"})的注解需要寫(xiě)在service的接口上
// 注意java的自動(dòng)代理必須存在接口
// TransactionAspect 是事務(wù)切面 ,你也可以實(shí)現(xiàn)自己的切面比如日志的Aspect,實(shí)現(xiàn)Aspect接口
// 再private UserService userService = AspectFactory.newInstance(new UserServiceImpl(), new TransactionAspect(),new LogAspect());
private UserService userService = AspectFactory.newInstance(new UserServiceImpl(), new TransactionAspect());5.極簡(jiǎn)的權(quán)限設(shè)計(jì),可以通過(guò)cache支持分布式session,你只需要實(shí)現(xiàn)一個(gè)簡(jiǎn)單接口和添加一個(gè)攔截器,即可實(shí)現(xiàn)基于url的權(quán)限設(shè)計(jì)
public void configInterceptor(InterceptorLoader interceptorLoader) {
//權(quán)限攔截器 放在第一位 第一時(shí)間判斷 避免執(zhí)行不必要的代碼
interceptorLoader.add(new SecurityInterceptor(new MyAuthenticateService()));
}
//實(shí)現(xiàn)接口
public class MyAuthenticateService implements AuthenticateService {
//登陸時(shí) 通過(guò)name獲取用戶的密碼和權(quán)限信息
public Principal findByName(String name) {
DefaultPasswordService defaultPasswordService = new DefaultPasswordService();
Principal principal = new Principal(name, defaultPasswordService.hash("123"), new HashSet<String>() {
{
add("api");
}
});
return principal;
}
//基礎(chǔ)的權(quán)限總表 所以的url權(quán)限都放在這兒 你可以通過(guò) 文件或者數(shù)據(jù)庫(kù)或者直接代碼 來(lái)設(shè)置所有權(quán)限
public Set<Credential> loadAllCredentials() {
Set<Credential> credentials = new HashSet<Credential>();
credentials.add(new Credential("GET", "/api/v1.0/users**", "users"));
return credentials;
}
}6.極簡(jiǎn)的緩存設(shè)計(jì),可擴(kuò)展,非常簡(jiǎn)單即可啟用model的自動(dòng)緩存功能
//啟用緩存并在要自動(dòng)使用緩存的model上
//config application.properties app.cacheEnabled=true
//開(kāi)啟緩存@Table(name = "sec_user", cached = 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.上傳文件,注解配置把文件寫(xiě)到服務(wù)器
@POST("/files")
@FILE(dir = "/upload/")
//配置上傳文件的相關(guān)信息
public UploadedFile file(UploadedFile file) {
return file;
}9.當(dāng)然也是支持傳統(tǒng)的web開(kāi)發(fā),你可以自己實(shí)現(xiàn)數(shù)據(jù)解析,在config里添加自定義的解析模板
public void configConstant(ConstantLoader constantLoader) {
// 通過(guò)后綴來(lái)返回不同的數(shù)據(jù)類型 你可以自定義自己的 render 如:FreemarkerRender
//默認(rèn)已添加json和text的支持,只需要把自定義的Render add即可
// constantLoader.addRender("json", new JsonRender());
}二、運(yùn)行EXAMPLE示例:
1.在本地mysql數(shù)據(jù)庫(kù)里創(chuàng)建demo,example數(shù)據(jù)庫(kù),對(duì)應(yīng)application.properties的數(shù)據(jù)庫(kù)配置
2.運(yùn)行resty-example下的pom.xml->flyway-maven-plugin:migrate,自動(dòng)根具resources下db目錄下的數(shù)據(jù)庫(kù)文件生成數(shù)據(jù)庫(kù)表結(jié)構(gòu)
3.運(yùn)行resty-example下的pom.xml->tomcat6-maven-plugin:run,啟動(dòng)example程序
提醒:推薦idea作為開(kāi)發(fā)ide,使用分模塊的多module開(kāi)發(fā)
以上就是Resty開(kāi)發(fā)restful版本的Jfinal深入研究的詳細(xì)內(nèi)容,更多關(guān)于Resty開(kāi)發(fā)restful版Jfinal的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
java注解的類型知識(shí)點(diǎn)總結(jié)
在本篇文章里小編給大家整理了一篇關(guān)于java注解的類型知識(shí)點(diǎn)總結(jié)內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2021-03-03
SpringBoot JPA實(shí)現(xiàn)查詢多值
這篇文章主要為大家詳細(xì)介紹了SpringBoot JPA實(shí)現(xiàn)查詢多值,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-08-08
springboot封裝JsonUtil,CookieUtil工具類代碼實(shí)例
這篇文章主要介紹了springboot封裝JsonUtil,CookieUtil工具類過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09
使用spring aop 統(tǒng)一捕獲異常和寫(xiě)日志的示例demo
本文通過(guò)一個(gè)小demo給大家介紹spring AOP 實(shí)現(xiàn)的異常捕獲和日志的方法技巧,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2021-08-08
java實(shí)現(xiàn)通過(guò)綁定郵箱找回密碼功能
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)通過(guò)綁定郵箱找回密碼功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02

