What to do if the dependent service fails? Millions of projects are going to be roadshow demo tomorrow

What to do if the dependent service fails? Millions of projects are going to be roadshow demo tomorrow

This is the 6th day that I participated in the Wenwen Challenge. For details of the event, please view: Wenwen Challenge

What to do if the dependent service fails? Millions of projects are going to be roadshow demo tomorrow


Sometimes entrepreneurs will develop and produce some projects, such as some apps, and go to the entrepreneurial park to show them.

But things were unsatisfactory, some services that the App relied on failed, and the first screen (the homepage couldn't be logged in for any reason).

Originally, I entered the App to place an order and submit the result. I got stuck in the payment pop-up window. If I can't proceed to the next step, the demo will definitely not proceed smoothly.

This is the end, and the financing of several million is about to fly!

In fact, the question is: the other party's service is offline, and the development on hand has not been completed. How to continue is the same!

Let s start to explain. In terms of calling a third-party payment service by an App, please read it carefully. At the end of the article, there is a programming column prepared by the blogger, and a lot of development and learning links are attached.

I haven't started a business, and I don't need a demo, so I won't run into this problem?

Generalization of the above problem means that students who are engaged in development often encounter a problem: the interface of the docking party is not ready yet, and the boss is still urging it repeatedly, even pressing the second and third projects!

Or, if the other party s website is hanging up, what should I do if I have to proceed with the project?

Therefore, whether this problem is front-end, back-end, or App, as long as your system has other system dependencies, usually other process calls that are not the application process, WebAPI calls, front-end cross-domain calls, etc., can be unified into this category Invoke the event.

Let's talk about how to solve it.


Modify the code of your own App

This is to add a toggle pattern to your own code and turn it on when developing a certain debugging! As shown in the figure below, a switch calls or requests its own analog data service.

If the services of others have little impact on your application, you can use the following code to proceed.

Lei Xuehui Demonstration Time: How to add switches/Toggle

Code in the existing App project:

//Lei Xuehui CSDN Demo code: //This method calls the interface of other companies (third parties) function callOtherServiceFromExternalCompany () { axios.get( 'http:///a-legacy-company-that-provide-unstable-api/api/v1/godBlessYouGetData' ).then(resp = >{ handleOnData(resp.data); }); } //handleOnData function: app is currently used to receive other data service function handleOnData ( Data ) { //omitted, where I is the subsequent process after the data service company to get others. //Omit N lines of code. } Copy code

The above code is very intuitive. After calling the third-party service, it triggers the call to handleOnData in this application.

This can be a third-party payment platform, you can use your own application to get the payment result and then enter the next order logistics arrangement, etc. (Or the App can also trigger the recalculation of the drawing interface by other people s data)

Code in the application after transformation:

//Lei Academic Committee CSDN Demo code: var flag = process.env.NODE_ENV //Get NODE_ENV from the environment variable, and switch the branch of code call according to this variable. function callOtherServiceFromExternalCompany () { if (flag) { //This is the switch we added var mockData = generateMockData() //Generate the mock data needed for the service handleOnData(mockData) } else { axios.get( 'http:///a-legacy-company-that-provide-unstable-api/api/v1/godBlessYouGetData' ).then(resp = >{ handleOnData(resp.data); }); } } //Here is the code of your own project without any modification. //handleOnData function: app is currently used to receive other data service function handleOnData ( Data ) { //omitted, where I is the subsequent process after the data service company to get others. //Omit N lines of code. } Copy code

This is solved, the specific value of the flag is set in the environment variable.

This approach can solve the problem of a small amount of dependence.

Usually there is not just an interface call between the system and the system! Too much can make this code look messy!

The more third-party services are called, a lot of switch codes appear in the code, which looks like layers of nesting dolls. (The switch is connected in series and then connected in series)

In the end your system looks like the picture below and cannot be maintained!

(Picture from: www.sohu.com/a/162197488...

How do you ask the students behind to take over? I must not dare to modify the code!

Let me talk about the second one.

Mirror copy third-party site interface

What do you mean?

By analogy, the original routing network name at home is: Lei Xuehui Wifi, the router is broken, then buy a new router and set the network name to: Lei Xuehui Wifi, the same password. Then our mobile phones and computers can be connected normally.

Just like hacker phishing, a highly imitation service interface is imitated, and the interface allows your service to continue to use normally without perception.

(The picture comes from the Internet: m.sohu.com/a/256230090...

This talk is about proxying the dependent services through technical means, and transferring all the calls to the simulated server developed by myself. Some novices may not understand that the third party here is the service of others.

In this way, you can try not to modify your own application code or modify it as little as possible (not to add branching to the code), usually to configure the gateway or modify the configuration to call a backup service (or a third-party service simulated by yourself).

If there is a third-party backup service, theoretically only the configuration of the originally called site needs to be modified to a backup site, without any code modification.

What we will discuss more here is the situation where there is no backup site/service. There are two approaches here, but of course the essence is the same.

Partial mirroring to simulate the other party's interface

Partial mirroring simulates the interface of the other party. When the other party has thousands of interfaces called by this system, it does not provide a method to copy the complete test environment.

This strategy can only be adopted. 1. call the interface from the entrance and mock (simulate processing) first
so that at least the login interface can be logged in, so that at least the company's demo can be made.

Then select the key interface for quick copy! This method is also suitable for the third-party service is a large site, he has a situation where a sub-service is down.

Lei Xuehui Demonstration Time: How to Partially Simulate

Well, here we will show the previous UI service, and the link will be posted after the code.

Start the UI service directly, because the background product service is not started, so it shows here: the back-end service is offline!

Write a partial mirror (Mock)

//Lei Xue Committee-CSDN-Code Demo const express = require ( 'express' ); const cors = require ( 'cors' ); const {createProxyMiddleware} = require ( 'http-proxy-middleware' ); //Lei Xue Commission -CSDN-Code Demo: Create a web service here const app = express(); app.use(cors()); //01 We intercepted and simulated the partial interface app.use( '/products' , function ( req,res ) { console .log( 'Lei Xuewei : Here we call our agent interface:' ,req.originalUrl) res.status( 200 ).send(()); // Anything on the hour will do }) //02 Other calls still go to this website http://a-legacy-company-that-provide-unstable-api //Here the request for/otherApi is forwarded to the original site through the proxy. app.use( '/otherApi' , createProxyMiddleware({ target : 'http:///a-legacy-company-that-provide-unstable-api/api/v1/godBlessYouGetData' , changeOrigin : true })); app.listen( 8081 ); copy the code

Here we see the 01 code segment: intercept all requests for/products in the current simulation service for simple processing (directly send an empty data {}).

In fact, third-party services are temporarily unavailable. What we need to pay attention to is to quickly simulate the interface (the processing corresponding to WebAPI) to facilitate our development and debugging.

When the project is almost developed, you still have to switch to the Zhengzhen service for joint debugging in the future! This needs to be remembered, don't love to fight!

Start the local proxy service, refresh the UI service on the right, the UI service shows that the third-party service is online (green) and prints the service data.

Copy the above code to save proxy8081.js, install and run as shown in the figure below.
Look at the effect, although the data is incomplete, but the UI service can be used normally.

Site-wide mirroring simulates the service interface of others

Fast site-wide simulation of each other's services

In this case, if the other party is offline, but provides the code and can run, then run it directly and configure the network host mapping (host mapping site: a-legacy-company-that-provide-unstable-api to the local machine ip)

Look, now the machine can access the interface of the site: http://a-legacy-company-that-provide-unstable-api:8081/products

readers can also take the proxy8081.js above and slightly adjust it to the whole site mirroring mode. But all interfaces of third-party services need to be written.

const express = require ( 'express' ); const cors = require ( 'cors' ); const {createProxyMiddleware} = require ( 'http-proxy-middleware' ); //Lei Academic Committee-CSDN-Code Demo const app = express (); app.use(cors()); //01 requires proxy interface one app.use( '/products' , function ( req,res ) { console .log( 'Lei Xuewei : Our proxy interface is called here:' ,req.originalUrl) res.status( 200 ).send(()); // Anything on the hour will do }) //02 requires proxy interface two app.use( '/api02' , function ( req,res ) { console .log( 'Lei Xuewei : Our proxy interface is called here:' ,req.originalUrl) res.status( 200 ).send(()); // Anything on the hour will do }) //Omit 10,000 lines of code to implement multiple interface agents. //Proxy the Nth interface app.use( '/lastApi' , function ( req,res ) { console .log( 'Lei Xuewei : Our proxy interface is called here:' ,req.originalUrl) res.status( 200 ).send(()); // Anything on the hour will do }) app.listen( 8081 ); copy the code

From this point of view, do you feel that site-wide mirroring can be done quickly when the complete code of third-party services is provided.

But in many cases, the code of third-party services given by others may not be able to run. Then this whole site proxy/mirror requires a lot of code, which is basically to quickly implement the background interface of the entire third-party site.

Okay, let s stop here and see how the agency works:

Architecture without agent: Architecture

with agent:

There is an additional proxy layer in the middle, which is the proxy code we wrote or can also be understood as a network mapping layer.

So, what's the point of the complexity of the site-wide agent?

  • There is no background code/the only option to rely on service agents

When we get a project without back-end code or back-end services, we can only be tough.

This is very useful, you can quickly run the project! If it is a valuable UI or App project, you can run it quickly and learn about the principles and business processes of other excellent applications by checking the running effects.

  • What you get is an App, or a packaged project

You don't have the environment or enough knowledge to add toggle and recompile.
At this time, you can launch the human sea tactics to see how many interfaces the App uses, assign the interfaces to rapid development, and let the App run.

Readers who know this will know that this is just an example of a scenario, and many reverse engineering people will do the same.


This article describes several methods for simulating third-party services, as well as several methods for redirecting requests (traffic) to simulated test services.

I believe all developers will encounter similar problems.

We must stay awake and choose the appropriate simulation method! Get twice the result with half the effort.

Well, students who are interested in NodeJS or programming can check it out: NodeJS series by Lei Xuewei

In addition, recommend the excellent Nginx: www.nginx.com/ & https://www.nginx.cn/doc/

Nginx can quickly implement website proxy through configuration, which is quite simple. This article only shows a small amount of code.

This article can give you the idea of solving dependencies and reverse server deduction.

Looking forward to the comments, if you feel good, please forward and support the collection!

Continuous learning and continuous development, I am Lei Xuehui, thank you for reading.

Reference link:

UI project code used above: blog.csdn.net/geeklevin/a...

FeatureToggle explanation by Martin Great God: martinfowler.com/bliki/Featu...

Recommend MockJS to quickly generate simulation data: mockjs.com/examples.ht...

This is the practical guide of FeatureToggle: www.flagship.io/feature-tog...