preface

Most writing sites have a feature that allows you to edit real-time. It is a very practical function for users. As a personal blog, although the use is not so obvious, but still want to achieve this function, as a practice hand.

Implementation approach

  1. useWebSocketTo carry out real-time communication between browser and server;
  2. Server usageRedisTo cache articles that are edited in real time (frequent changes to articles while editing, frequent database reads and writes are not a good solution);
  3. The server uses a scheduled task (e.g., 3am every day) that willRedisCached data is stored toMySQLDatabase;
  4. When the browser enters the new article page for the first time, useWebSocketGet data from the server (first fromRedisIf not, then fromMySQLDatabase lookup);
  5. When the browser enters the page for editing articles for the first time, there is no need to obtain data from the server.
  6. useVue.jsWatch to monitor the change of the article, used when the changeWebSocketSend data to the server.
  7. Delete the article as you save itRedisandMySQLData saved in real time.

The source code

Talk is cheap. Show me the code.

instructions

  1. This function is only for personal blog background use, there is no multi-account system, so Redis and MySQL are to save a record. If you need to save by different users, you need to develop your own.

  2. More code, the specific code will not be posted, interested can go to my GitHub to view the source code. This is just to illustrate the usefulness of the code in each file.

1. /server/util/draft-socketio.js

Server WebSocket service, using the socket. IO library.

2. /server/util/draft-redis.js

Redis public methods for set and GET.

3. /server/util/redis-mysql.js

  • redisToMysqlTask: Timing synchronizationRedisData to theMySQLThe data method is usednode-scheduleLibrary.
  • getDraftPostFromMysql: RedisWhen there is no data inMySQLTo query data.
  • clearDraftPostOfMysqlFrom:MySQLDelete the data (after the article is saved).

4. /src/main.js

IO and vUE -socket. IO and socket. IO -client libraries are used.

import VueSocketio from 'vue-socket.io';
import socketio from 'socket.io-client';

Vue.use(VueSocketio, socketio('http://localhost:9000', {
  path: '/testsocketiopath'
}));
Copy the code

5. /src/pages/Edit.vue

Use WebSocket to get data from the server and transfer the data to the server in real time for saving.

conclusion

  1. The whole function is essentiallyWebSocket,RedisandMySQLThe use of these several have been used before, so it is relatively easy to develop. The most important thing is to think of a solution first.
  2. And finally, as usual, fork and star.