前后端分離同步開發時,如果前端需要等后端把接口都開發完了再去動工的話,項目周期會拉長。
以前開發時,一般前期是先把接口文檔寫的差不多了,要么是讓前端自己構造模擬數據,要么是后端在開個控制器專門提供模擬數據,用起來都不是那么爽,直到接觸了 wiremock ,既不用寫代碼,又能方便靈活的提供模擬數據。
這里講的模式是 將 wiremock 作為獨立進程服務,來為調用者提供各個接口數據,非常好用
首先: 下載一個 jar 包在 wiremock 的官網上,http://wiremock.org/docs/running-standalone/
下載下來后,直接通過 java -jar wiremock-standalone-2.18.0.jar 啟動,
寫了個簡單的腳本啟動
[root@VM_32_12_centos wiremock]# cat server.sh #!/bin/sh nohup java -jar wiremock-standalone-2.18.0.jar --port 6666 > /dev/null 2>&1 & [root@VM_32_12_centos wiremock]#
啟動后的項目結構如下: 會多了 __files 和 mappings 兩個目錄

mappings 目錄,用來存放映射規則
__files 目錄,用來存放擴展文件
這里是 mappings 中的兩個映射文件

附一個官網的 mapping 文件
{ "request": { "method": "GET", "url": "/api/mytest" }, "response": { "status": 200, "body": "More content\n" } }
這里放的 /api/mytest 接口響應內容對應的文件
 
當配置好了后,可以試下模擬接口是否能夠訪問了:
curl http://127.0.0.1:6666/api
或者
curl http://127.0.0.1:6666/api/mytest
如果響應的是: No response could be served as there are no stub mappings in this WireMock instance.
那就需要把 wiremock 的服務重新啟動一下了,重啟后發現返回的數據就是所配置的內容啦
最后,可以通過 NGINX 反向代理暴露出模擬的接口(非必須)
location ^~/mock/ { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:6666/; }
這樣就能夠通過 這樣的方式訪問啦
http://xxx.com/mock/api
或者
http://xxx.com/mock/api/mytest
顯得更加靈活
