地平線之旅01 — Horizon初探

Horizon

之前的文章我們介紹了Horizon例获,無需編寫后端代碼闪彼,就能構(gòu)建實時應用壳快,今天我們繼續(xù)我們的地平線之旅洼专!

安裝RethinkDB

使用Horizon首先需要安裝RethinkDB,并且版本在2.3.1之上者祖,這里我們以OSX為例使用homebrew安裝:

brew update
brew install rethinkdb

如果之前安裝過老版本的rethinkdb立莉,可以使用brew upgrade rethinkdb來更新。目前最新版本為2.3.3七问。

安裝Horizon CLI

首先我們安裝Horizon CLI蜓耻,它提供了hz命令:

npm install -g horizon

這里我們用到Horizon的命令行工具提供的兩個指令:

  • init [directory]: 初始化一個Horizon應用
  • serve: 運行服務端

創(chuàng)建Horizon項目

$ hz init example_app
Created new project directory example_app
Created example_app/src directory
Created example_app/dist directory
Created example_app/dist/index.html example
Created example_app/.hz directory
Created example_app/.hz/config.toml

我們看一下項目結(jié)構(gòu):

$ tree example_app
example_app/
├── .hz
│   └── config.toml
├── dist
│   └── index.html
└── src
  • dist 里面是靜態(tài)文件。
  • src使你構(gòu)建系統(tǒng)的源文件械巡。
  • dist/index.html是示例文件刹淌。
  • .hz/config.toml是一個toml配置文件。

啟動Horizon服務器

我們可以使用hz serve --dev來啟動服務器讥耗。

App available at http://127.0.0.1:8181
RethinkDB
   ├── Admin interface: http://localhost:52936
   └── Drivers can connect to port 52935
Starting Horizon...

可以看到有勾,增加了--dev后,不僅啟動了服務器葛账,還有RethinkDB的數(shù)據(jù)庫柠衅,我們可以通過不同的端口來訪問后臺皮仁。

RethinkDB 后臺

--dev這個標簽代表了下面這些設置:

  1. 自動運行RethinkDB (--start-rethinkdb)
  2. 以非安全模式運行籍琳,不要求SSL/TLS (--secure no)
  3. 關閉了權限系統(tǒng) (--permissions no)
  4. 表和索引如果不存在被自動創(chuàng)建 (--auto-create-collection
    and --auto-create-index)
  5. 靜態(tài)文件將在dist文件夾被serve (--serve-static ./dist)

如果不使用--dev標簽,在生產(chǎn)環(huán)境里贷祈,你需要使用配置文件.hz/config.toml來設置這些參數(shù)趋急。

連接Horizon

我們來看一下index.html

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <script src="/horizon/horizon.js"></script>
    <script>
      var horizon = Horizon();
      horizon.onReady(function() {
        document.querySelector('h1').innerHTML = 'App works!'
      });
      horizon.connect();
    </script>
  </head>
  <body>
   <marquee><h1></h1></marquee>
  </body>
</html>

var horizon = Horizon()初始化了Horizon對象,它只有一些方法势誊,包括連接相關的事件和實例化Horizon的集合呜达。

onReady是一個事件處理器,它再客戶端成功連接到服務端的時候被執(zhí)行粟耻。我們的連接僅僅在<h1>標簽中添加了"App works!"查近。它只是檢測了Horizon是否工作眉踱,還并沒有用到RethinkDB。

Example App

Horizon集合

Horizon的核心是集合(Collection對象)霜威,使你能夠獲取谈喳、存儲和篩選文檔記錄。許多集合方法讀寫文檔返回的是RxJS Observables戈泼。關于Rx的一些基本只是可以看RXJS 介紹

// 創(chuàng)建一個"messages"集合
const chat = horizon("messages");

使用store方法存儲

let message = {
  text: "What a beautiful horizon!",
  datetime: new Date(),
  author: "@dalanmiller"
}

chat.store(message);

使用fetch方法讀取

chat.fetch().subscribe(
  (items) => {
    items.forEach((item) => {
      // Each result from the chat collection
      //  will pass through this function
      console.log(item);
    })
  },
  // If an error occurs, this function
  //  will execute with the `err` message
  (err) => {
    console.log(err);
  })

這里使用了RxJS的subscribe方法來獲取集合中的條目婿禽,并且提供了一個錯誤處理器。

刪除數(shù)據(jù)

刪除集合中的條目大猛,我們可以使用removeremoveAll

// These two queries are equivalent and will remove the document with id: 1
chat.remove(1).subscribe((id) => { console.log(id) })
chat.remove({id: 1}).subscribe((id) => {console.log(id)})

// Will remove documents with ids 1, 2, and 3 from the collection
chat.removeAll([1, 2, 3])

你可以級聯(lián)subscribe函數(shù)到remove函數(shù)后面扭倾,來獲取響應和錯誤處理器。

觀察變化

我們可以使用watch來監(jiān)聽整個集合挽绩、查詢或者單個條目膛壹。這讓我們能夠隨著數(shù)據(jù)庫數(shù)據(jù)的變化立即變更應用狀態(tài)。

// Watch all documents. If any of them change, call the handler function.
chat.watch().subscribe((docs) => { console.log(docs)  })

// Query all documents and sort them in ascending order by datetime,
//  then if any of them change, the handler function is called.
chat.order("datetime").watch().subscribe((docs) => { console.log(docs)  })

// Watch a single document in the collection.
chat.find({author: "@dalanmiller"}).watch().subscribe((doc) => { console.log(doc) })

默認情況下唉堪,watch返回的Observable會接收整個文檔集合當有一個條目發(fā)生變化恢筝。這使得VueReact這類框架很容易集成,它允許你使用Horizon新返回的數(shù)組替換現(xiàn)有的集合拷貝巨坊。

我們來看一下示例:

let chats = [];

// Query chats with `.order`, which by default is in ascending order
chat.order("datetime").watch().subscribe(

  // Returns the entire array
  (newChats) => {

    // Here we replace the old value of `chats` with the new
    //  array. Frameworks such as React will re-render based
    //  on the new values inserted into the array.
    chats = newChats;
  },

  (err) => {
    console.log(err);
  })

更多Horizon+React示例可以參見complete Horizon & React example撬槽。

結(jié)合所有

現(xiàn)在我們結(jié)合上述知識點,構(gòu)建一個聊天應用趾撵,消息以倒序呈現(xiàn):

let chats = [];

// Retrieve all messages from the server
const retrieveMessages = () => {
  chat.order('datetime')
  // fetch all results as an array
  .fetch()
  // Retrieval successful, update our model
  .subscribe((newChats) => {
      chats = chats.concat(newChats);
    },
    // Error handler
    error => console.log(error),
    // onCompleted handler
    () => console.log('All results received!')
    )
};

// Retrieve an single item by id
const retrieveMessage = id => {
  chat.find(id).fetch()
    // Retrieval successful
    .subscribe(result => {
      chats.push(result);
    },
    // Error occurred
    error => console.log(error))
};

// Store new item
const storeMessage = (message) => {
   chat.store(message)
    .subscribe(
      // Returns id of saved objects
      result => console.log(result),
      // Returns server error message
      error => console.log(error)
    )
};

// Replace item that has equal `id` field
//  or insert if it doesn't exist.
const updateMessage = message => {
  chat.replace(message);
};

// Remove item from collection
const deleteMessage = message => {
  chat.remove(message);
};

chat.watch().subscribe(chats => {
    renderChats(allChats)
  },

  // When error occurs on server
  error => console.log(error),
)

你也可以獲取客戶端與服務端是否連接的通知:

// Triggers when client successfully connects to server
horizon.onReady().subscribe(() => console.log("Connected to Horizon server"))

// Triggers when disconnected from server
horizon.onDisconnected().subscribe(() => console.log("Disconnected from Horizon server"))

在這里侄柔,你編寫了一個實時聊天應用,而且不用書寫一行后端代碼占调。

Horizon與現(xiàn)有應用結(jié)合

Horizon有兩種方式與現(xiàn)有應用結(jié)合:

  1. 使用Horizon服務器提供的horizon.js
  2. 添加@horizon/client的依賴

這里推薦的是第一種做法暂题,因為它將預防任何潛在的client和Horizon server的版本沖突。當然究珊,如果你使用Webpack或其他相似的構(gòu)建工具薪者,可以將client庫作為NPM依賴(npm install @horizon/client
)。

<script src="localhost:8181/horizon/horizon.js"></script>

// Specify the host property for initializing the Horizon connection
const horizon = Horizon({host: 'localhost:8181'});

參考

[1] http://www.reibang.com/p/8406baeb01c5
[2] http://horizon.io/docs/getting-started/

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末剿涮,一起剝皮案震驚了整個濱河市言津,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌取试,老刑警劉巖悬槽,帶你破解...
    沈念sama閱讀 218,682評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異瞬浓,居然都是意外死亡初婆,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,277評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來磅叛,“玉大人屑咳,你說我怎么就攤上這事”浊伲” “怎么了乔宿?”我有些...
    開封第一講書人閱讀 165,083評論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長访雪。 經(jīng)常有香客問我详瑞,道長,這世上最難降的妖魔是什么臣缀? 我笑而不...
    開封第一講書人閱讀 58,763評論 1 295
  • 正文 為了忘掉前任坝橡,我火速辦了婚禮,結(jié)果婚禮上精置,老公的妹妹穿的比我還像新娘计寇。我一直安慰自己,他們只是感情好脂倦,可當我...
    茶點故事閱讀 67,785評論 6 392
  • 文/花漫 我一把揭開白布番宁。 她就那樣靜靜地躺著,像睡著了一般赖阻。 火紅的嫁衣襯著肌膚如雪蝶押。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,624評論 1 305
  • 那天火欧,我揣著相機與錄音棋电,去河邊找鬼。 笑死苇侵,一個胖子當著我的面吹牛赶盔,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播榆浓,決...
    沈念sama閱讀 40,358評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼于未,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了陡鹃?” 一聲冷哼從身側(cè)響起烘浦,我...
    開封第一講書人閱讀 39,261評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎杉适,沒想到半個月后谎倔,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體柳击,經(jīng)...
    沈念sama閱讀 45,722評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡猿推,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蹬叭。...
    茶點故事閱讀 40,030評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡藕咏,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出秽五,到底是詐尸還是另有隱情孽查,我是刑警寧澤,帶...
    沈念sama閱讀 35,737評論 5 346
  • 正文 年R本政府宣布坦喘,位于F島的核電站盲再,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏瓣铣。R本人自食惡果不足惜答朋,卻給世界環(huán)境...
    茶點故事閱讀 41,360評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望棠笑。 院中可真熱鬧梦碗,春花似錦、人聲如沸蓖救。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,941評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽循捺。三九已至斩例,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間从橘,已是汗流浹背樱拴。 一陣腳步聲響...
    開封第一講書人閱讀 33,057評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留洋满,地道東北人晶乔。 一個月前我還...
    沈念sama閱讀 48,237評論 3 371
  • 正文 我出身青樓,卻偏偏與公主長得像牺勾,于是被迫代替她去往敵國和親正罢。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,976評論 2 355

推薦閱讀更多精彩內(nèi)容

  • Horizon使用JSON Web Tokens實現(xiàn)用戶的認證驻民,不管你是不是使用Horizon進行開發(fā)翻具,你都應該了...
    時見疏星閱讀 648評論 1 0
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn)回还,斷路器裆泳,智...
    卡卡羅2017閱讀 134,659評論 18 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,162評論 25 707
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,822評論 6 342
  • 你走在前面 我看不見你 你轉(zhuǎn)過身來 卻仍難觸及 我們之間沒有幾億光年的距離 只是這濃塵霧靄里 你看不見我 我看不見...
    小北東南西西西閱讀 284評論 0 1