Resty開發(fā)restful版本的Jfinal深入研究
前言
自發(fā)現(xiàn)了resty后,一直進(jìn)行深入考究到深夜3點才睡,只想說這6個小時的體驗博主內(nèi)心是滿足的!說resty是restful版的Jfinal之Resty,其實有點過了,只是大部分人知道Jfinal,不一定知道還有個resty,resty的框架設(shè)計大量借鑒了Jfinal極簡開發(fā)的思想,先拋開resty是否有重復(fù)造輪子之嫌!就作者寫了大量的Jfinal插件后,提煉出針對restful開發(fā)的resty來,我覺得還是有意義的。而且,正好博主近期在開發(fā)一個app的一個項目,需要寫接口給客戶端調(diào)用,對比下來發(fā)現(xiàn)resty針對這個事情幫你想好了很多東西。對于接觸過Jfinal的朋友來說,使用resty開發(fā)是件so easy的事情, 下面是官方實例,大家感受下
作者的Jfinal插件地址:https://github.com/Dreampie/jfinal-dreampie
resty開發(fā)文檔:https://dreampie.gitbooks.io/
官方實例
maven使用方式:
1.添加依賴包
<dependency> <groupId>cn.dreampiegroupId> <artifactId>resty-routeartifactId> <version>1.0version> <dependency>
2.如果使用帶有-SNAPSHOT后綴的包,請?zhí)砑釉搨}庫
<repositories> <repository> <id>oss-snapshotsid> <url>https://oss.sonatype.org/content/repositories/snapshotsurl> <releases> <enabled>trueenabled> releases> <snapshots> <enabled>trueenabled> snapshots> repository> <repositories>
一、獨有優(yōu)點:
重大更新:
1.2.0更新內(nèi)容:使用header來控制api版本,基于數(shù)據(jù)源的讀寫分離,更簡單的tableSetting.詳情查看
1.1.0版本重大更新:快速接入spring,緩存,加密,header,XForwardedSupports等,詳情查看
Record的時代已經(jīng)到來,你完全不用使用任何的model來執(zhí)行你的數(shù)據(jù)
//創(chuàng)建record的執(zhí)行器 針對sec_user表 并開啟緩存 Record recordDAO = new Record("sec_user"); //使用當(dāng)前數(shù)據(jù)源和表數(shù)據(jù) new一個對象來保存數(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) //分頁查詢 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,實現(xiàn)快速操作數(shù)據(jù)
Model支持動態(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ù)庫和全局參數(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ù)庫的配置精簡 自動從文件讀取參數(shù) 只需配置model掃描目錄 和dsmName public void configPlugin(PluginLoader pluginLoader) { //第一個數(shù)據(jù)庫 ActiveRecordPlugin activeRecordPlugin = new ActiveRecordPlugin(new DruidDataSourceProvider("default"), true); activeRecordPlugin.addIncludePaths("cn.dreampie.resource"); pluginLoader.add(activeRecordPlugin); }
1.極簡的route設(shè)計,完全融入普通方法的方式,方法參數(shù)就是請求參數(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.極簡的activerecord設(shè)計,數(shù)據(jù)操作只需短短的一行,支持批量保存對象
//批量保存 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.極簡的客戶端設(shè)計,支持各種請求,文件上傳和文件下載(支持?jǐn)帱c續(xù)傳)
Client client=null; //創(chuàng)建客戶端對象 //啟動resty-example項目,即可測試客戶端 String apiUrl = "http://localhost:8081/api/v1.0"; //如果不需要 使用賬號登陸 //client = new Client(apiUrl); //如果有賬號權(quán)限限制 需要登陸 client = new Client(apiUrl, "/tests/login", "u", "123"); //該請求必須 登陸之后才能訪問 未登錄時返回 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 測試筆"); ClientResult uploadResult = client.build(uploadRequest).post(); System.out.println(uploadResult.getResult()); //download 支持?jǐn)帱c續(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ù)(使用場景:需要訪問多個數(shù)據(jù)庫的應(yīng)用,或者作為公司內(nèi)部的數(shù)據(jù)中間件向客戶端提供數(shù)據(jù)訪問api等)
// 在resource里使用事務(wù),也就是controller里,rest的世界認(rèn)為所以的請求都表示資源,所以這兒叫 resource @GET("/users") @Transaction(name = {"default", "demo"}) //多數(shù)據(jù)源的事務(wù),如果你只有一個數(shù)據(jù)庫 直接 @Transaction 不需要參數(shù) public User transaction() { //TODO 用model執(zhí)行數(shù)據(jù)庫的操作 只要有操作拋出異常 兩個數(shù)據(jù)源 都會回滾 雖然不是分布式事務(wù) 也能保證代碼塊的數(shù)據(jù)執(zhí)行安全} // 如果你需要在service里實現(xiàn)事務(wù),通過java動態(tài)代理(必須使用接口,jdk設(shè)計就是這樣) public interface UserService { @Transaction(name = {"demo"}) //service里添加多數(shù)據(jù)源的事務(wù),如果你只有一個數(shù)據(jù)庫 直接@Transaction 不需要參數(shù) public User save(User u);} // 在resource里使用service層的 事務(wù) // @Transaction(name = {"demo"})的注解需要寫在service的接口上 // 注意java的自動代理必須存在接口 // TransactionAspect 是事務(wù)切面 ,你也可以實現(xiàn)自己的切面比如日志的Aspect,實現(xiàn)Aspect接口 // 再private UserService userService = AspectFactory.newInstance(new UserServiceImpl(), new TransactionAspect(),new LogAspect()); private UserService userService = AspectFactory.newInstance(new UserServiceImpl(), new TransactionAspect());
5.極簡的權(quán)限設(shè)計,可以通過cache支持分布式session,你只需要實現(xiàn)一個簡單接口和添加一個攔截器,即可實現(xiàn)基于url的權(quán)限設(shè)計
public void configInterceptor(InterceptorLoader interceptorLoader) { //權(quán)限攔截器 放在第一位 第一時間判斷 避免執(zhí)行不必要的代碼 interceptorLoader.add(new SecurityInterceptor(new MyAuthenticateService())); } //實現(xiàn)接口 public class MyAuthenticateService implements AuthenticateService { //登陸時 通過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)限都放在這兒 你可以通過 文件或者數(shù)據(jù)庫或者直接代碼 來設(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.極簡的緩存設(shè)計,可擴(kuò)展,非常簡單即可啟用model的自動緩存功能
//啟用緩存并在要自動使用緩存的model上 //config application.properties app.cacheEnabled=true //開啟緩存@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.上傳文件,注解配置把文件寫到服務(wù)器
@POST("/files") @FILE(dir = "/upload/") //配置上傳文件的相關(guān)信息 public UploadedFile file(UploadedFile file) { return file; }
9.當(dāng)然也是支持傳統(tǒng)的web開發(fā),你可以自己實現(xiàn)數(shù)據(jù)解析,在config里添加自定義的解析模板
public void configConstant(ConstantLoader constantLoader) { // 通過后綴來返回不同的數(shù)據(jù)類型 你可以自定義自己的 render 如:FreemarkerRender //默認(rèn)已添加json和text的支持,只需要把自定義的Render add即可 // constantLoader.addRender("json", new JsonRender()); }
二、運行EXAMPLE示例:
1.在本地mysql數(shù)據(jù)庫里創(chuàng)建demo,example數(shù)據(jù)庫,對應(yīng)application.properties的數(shù)據(jù)庫配置
2.運行resty-example下的pom.xml->flyway-maven-plugin:migrate,自動根具resources下db目錄下的數(shù)據(jù)庫文件生成數(shù)據(jù)庫表結(jié)構(gòu)
3.運行resty-example下的pom.xml->tomcat6-maven-plugin:run,啟動example程序
提醒:推薦idea作為開發(fā)ide,使用分模塊的多module開發(fā)
以上就是Resty開發(fā)restful版本的Jfinal深入研究的詳細(xì)內(nèi)容,更多關(guān)于Resty開發(fā)restful版Jfinal的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
springboot封裝JsonUtil,CookieUtil工具類代碼實例
這篇文章主要介紹了springboot封裝JsonUtil,CookieUtil工具類過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-09-09使用spring aop 統(tǒng)一捕獲異常和寫日志的示例demo
本文通過一個小demo給大家介紹spring AOP 實現(xiàn)的異常捕獲和日志的方法技巧,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2021-08-08