美文网首页
用Json Server + Docker完成Mock Serv

用Json Server + Docker完成Mock Serv

作者: 科学Jia | 来源:发表于2018-06-27 11:21 被阅读164次

从德国回来以后,就一直忙于各种事情,一不小心就快7月了。。。接着可能又要出差到匈牙利。。。

直接进入主题,在我目前的项目里,需要不断地从别的项目提供的服务里查询time series的数据,这种依赖关系导致的问题是,有时候取不到数据,就怀疑到底是自己的问题,还是对方服务的问题,搞得双方最后都很不愉快。其实,我一直不明白为什么,这个项目的leader一直坚持在Dev的环境里,一定要用真实的服务。于是我私下找时间用Json Server搭建了一个mock server,它可以让你用简单的js脚本或者提前构造好的Json文件,很轻松的实现一个你想要的mock server。

先把最新的代码贴出来:Mock Server代码-->-->GitHub地址,请点击

Json Server

顾名思义,首先看看它能做什么事情?
Create a db.json file

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}

Start JSON Server

$ json-server --watch db.json

Now if you go to http://localhost:3000/posts/1, you'll get

{ "id": 1, "title": "json-server", "author": "typicode" }

看完是不是觉得,对需要这种mock server的人简直就是一大福音。

Json Server的安装

npm install -g json-server

npm是nodejs的专属命令,有点像java里不得不提到maven。所以,请先安装nodejs,以前我只接触java,自从接触了nodejs以后,觉得它就是一把利器,非常快速轻量。

构建一个属于我的Json Server

  • 创建一个index.js文件, 它主要实现的是如下格式的json数据,也就是前面提到的项目里需要从别的服务里获取的timeseries数据格式。
[
    {
        "FPY": "201",
        "_time": "2018-06-26T09:08:01.132Z"
    },
    {
        "FPY": "202",
        "_time": "2018-06-26T09:08:06.133Z"
    }
]

这个js程序会不断创建上面这个数据可是的timeseries数据。

module.exports = () => {
  const data = {FPY:[],OUTPUT:[]}
  // Create 2 json format: FPY, OUTPUT
  let i = 0
  let timer = setInterval(() => {
      i += 1;
      data.FPY.push({ FPY: `${i+200}`, _time: new Date().toISOString()});
      data.OUTPUT.push({_time: new Date().toISOString(), OUTPUT: `${i+10}`})
  }, 5000);
  
  return data
}
  • 创建一个routes.json文件,用来关联真实请求的url和我自己创建的url之间的映射关系。
{
  "/timeseries/*/FPY?from=:from&to=:to&limit=:limit&select=:FPY":"/:FPY?_time_gte=:from&_time_lte=:to&_limit=:limit",
  "/timeseries/*/OUTPUT?from=:from&to=:to&limit=:limit&select=:OUTPUT":"/:OUTPUT?_time_gte=:from&_time_lte=:to&_limit=:limit",
  "/timeseries/*/OUTPUT?select=OUTPUT":"/OUTPUT?_sort=_time&_order=desc&_limit=1",
  "/timeseries/*/FPY?select=FPY":"/FPY?_sort=_time&_order=desc&_limit=1"
}

解释下这个文件的含义,e.g.真实发出请求的url长这个样子:

http://xxxx:8080/timeseries/2c9083b063007b4401641cb572f40018/OUTPUT?from=2018-06-19T16:50:00Z&to=2018-06-20T18:05:00Z&limit=5&select=FPY

把这个url提取特性如下:

/timeseries/*/FPY?from=:from&to=:to&limit=:limit&select=:FPY

其中*是通配符,
:from,
:to,
:limit,
:FPY
这4个类似于函数参数的作用,它可以把url请求来的真实值通过他们传递给后面的映射关系:

/:FPY?_time_gte=:from&_time_lte=:to&_limit=:limit

再讲讲_time_gte,_time_lte和_limit的作用是:得到一个range范围内的数据可以被查询出来,以及限制多少条数据可以被查询出来

  • 运行起来,用postman可以验证下正确性
json-server index.js --routes routes.json

再次升级,用Docker来跑上面的Json Server

以centos环境为例,需要安装docker,以及准备dockerfile。

  • dockerfile
FROM node:8
# Create app working directory

WORKDIR /usr/src/app

COPY ./package*.json .

RUN npm install
RUN npm install -g json-server

COPY . .

#EXPOSE 3001

CMD ["npm","start"]

其中package.json是nodejs里生成的东西,我的package.json内容如下:

{
  "name": "json-server",
  "version": "1.0.0",
  "description": "Mock Iot TimeSeries Data",
  "main": "index.js",
  "dependencies": {
    "json-server": "^0.14.0",
    "mysql": "^2.15.0"
  },
  "devDependencies": {},
  "scripts": {
    "start": "json-server index.js --port 3001 --host 0.0.0.0 --routes routes.json"
  },
  "author": "You Jia",
  "license": "ISC"
}

这里要注意的是必须要设置--host 0.0.0.0,如果默认为localhost,那么在container外面访问json server服务的时候会出现 Connection Reset by Peer的错误

Docker的官网给出的解释如下:

You may get this error when trying to access a web server running in a container. Empty reply from server is another common error.
Depending on what tool you use (curl, browser, etc.), you may get a different error, but the result is the same. Your web server isn’t returning back the page you expect.
You may have even tried to troubleshoot this error by installing curl inside of your container and then if you ran curl localhost:3000 or whatever port your server is running on, it worked as expected.
If that happened to you, chances are it’s because your web server is bound to localhost which means it will only be available inside of your container.
To fix this problem, bind your web server to 0.0.0.0 instead. This will allow anyone to connect to your web server as long as they have access to your network.
This is almost always what you want for a public facing web application.
Also as a bonus tip, don’t forget to publish -p 3000:3000 when running your container if you want it to be accessed on that port.

  • 完成这项工作需要的docker命令:
  1. 创建docker image
docker build -t node-json-server-app0 .
  1. 查看已经创建好的image
docker images
  1. 启动docker
docker run --name youjia17 -p 8081:3001 -d node-json-server-app0
  1. 查看是否已经跑起来了
docker ps
  1. 本地测试是否运行正常
curl -i localhost:8081

如果在这过程里出了什么问题,还可以进入container内部查看:

docker exec -it youjia17 /bin/bash

其他docker命令,
docker ps -a,
docker kill <container name/id>,
docker rm <container id>,
docker rmi <镜像id>

参考文献:

Json Server Github
Dockerizing a Node.js web app

相关文章

网友评论

      本文标题:用Json Server + Docker完成Mock Serv

      本文链接:https://www.haomeiwen.com/subject/lhxbyftx.html