当前位置:网站首页>How to design an interface?
How to design an interface?
2022-07-05 12:16:00 【Xujunsheng】
How to design an interface ?
Preface
Interfaces are essential to our system , It can be called the cornerstone of the system . I think a good interface needs to have the following aspects : Security 、 stability 、 Efficiency 、 Maintainability 、 Readability . Now let's discuss what issues need to be considered in designing a good interface according to these properties ?
Security
Security is of great importance to interfaces . Our common Web Vulnerabilities include :SQL Inject 、JSON Deserialization vulnerability 、XSS attack 、CSRF attack 、 File upload and download vulnerability 、DDoS attack 、 Weak password 、 Certificate Validation 、 The internal interface is exposed in the public network 、 Unauthorized access related vulnerabilities .
Preventive measures :
- data validation : Use filters 、 The interceptor verifies the input data ;
- Identity Authentication & session management : Use token protection for interfaces of important operations ;
- Secure storage : Using encryption algorithms :MD5、SHA256、3DES;
- IP White list 、 Log the interface request 、 Desensitization of sensitive data, etc .
stability
Interface stability includes two aspects: one is robust, the other is reliable , These two concepts are easy to confuse .
Robustness,
Robustness refers to the ability of an interface to handle errors .
It is reflected in several aspects : Interface current limiting 、 Downgrade 、 Interface response timeout processing 、 Retry and early warning mechanism .
Current limiting
Current limiting , Also known as flow control (Rate Limit). It means that the system is facing high concurrency , Or in the case of large traffic requests , Only specified events are allowed to enter , The excess will be denied service 、 To line up or wait for 、 Demotion, etc , So as to ensure the stability of the interface .
Common current limiting algorithms : Fixed window current limiting algorithm ( Counter )、 Sliding window current limiting algorithm 、 Leaky bucket algorithm 、 Token bucket algorithm .
For space reasons, I will not explain here , Let's open a separate chapter to introduce in detail .
Interface response timeout processing
This is often the case when interfacing with third-party interfaces , Because of unstable factors such as network
.
In this case, we can take : Set timeout 、 Interface retry mechanism 、 asynchronous 、 Early warning and other schemes .
And we can pass it :System Default mode 、StopWatch、AutoCloseable To count the response time of the interface , In order to monitor it .
reliability
Reliability design can mainly consider : idempotent 、 There are two aspects of transaction consistency .
Idempotency
Idempotent means that the execution result of any number of requests has the same impact as that of one request .
To put it bluntly, query operation will not affect the data itself no matter how many times it is queried , So the query itself is idempotent . But new operations , The database changes with each execution , So it's not idempotent .
There are many ways to solve idempotent problems , such as :
- insert before select
- Add pessimism lock :select … for update
- Lock in optimism : Add a... To the list timestamp perhaps version Field
- Add unique index
- Build a weight watch
- Add distribution lock :redis、zookeeper
Transaction consistency
A transaction is a set of ungroupable operations , These operations are either successful , Or cancel the execution .
Four characteristics of transactions (ACID): Atomicity 、 Uniformity 、 Isolation, 、 persistence .
The single database does not involve network interaction , Therefore, it is relatively simple to implement transactions between multiple tables (Spring Affairs are easily solved ), This kind of transaction is called local transaction .
When the performance of a single database reaches the bottleneck, it needs to carry out database and table separation and service-oriented transformation .
Distributed transaction is the participant of transaction 、 Servers that support transactions 、 Resource servers and transaction managers are located on different nodes of different distributed systems .
Single database transactions can easily meet the requirements of transactions ACID Four features , Provide strong consistency assurance , But distributed transactions should fully follow ACID Features can be difficult .
In order to pursue high availability and high throughput of distributed systems , The solution of distributed transaction generally provides final consistency .
Distributed transactions
We call transactions that provide ultimate consistency as flexible transactions , Flexible transactions generally follow the rules in the distributed domain BASE theory :
- BA:Basic Availability, Basic business availability .
- S:Soft state, The state of flexibility .
- E:Eventual consistency, Final consistency .
There are three scenarios for distributed transactions :
- Distributed transactions across databases
- Cross service distributed transactions
- Hybrid distributed transaction
Common distributed transaction solutions :
- XA Two-phase commit
- TCC Pattern : Support TCC The open source frameworks for transactions are :ByteTCC、Himly、TCC-transaction.
- Saga
- Message based distributed transaction : Scheme based on transaction message 、 Local message based solutions
- Distributed transaction middleware :Seata
Efficiency
We can use multithreading to make full and rational use of system resources , Using cache can improve response speed 、
The implementation of multithreading is inseparable from two classes :Thread、Runnable.
At the same time, we can also use Future and Callable Get the execution result of the child thread .
Using thread pools, you can manage and reuse threads , Reduce the context switching and other problems caused by frequent thread creation .
When it comes to multithreading, we have to talk about thread safety .
Thread safety problem
Two scenarios of thread safety :
- Data contention : Write two data at the same time , The data of one party is either discarded or written incorrectly ;
- Competitive conditions : Execution order , For example, to read the contents of a file , Then naturally, after this document is written , Suppose the threads don't work well , I'll read it before you finish writing , This will cause errors in order .
Thread safety issues only occur in multithreaded environments , Single thread serial execution does not have this problem .
Ensure thread safety in high concurrency scenarios , There are four dimensions to consider :
- Data is visible in a single thread , such as ThreadLocal;
- Read only objects ,final
- Thread safety class :StringBuffer、ConcurrentHashMap
- Synchronization and lock mechanism :synchronized、Lock etc. .
You should also pay attention to deadlock in multithreaded scenarios .
Maintainability
Maintainability can also be called extensibility . This requires a good design of the interface at the design level .
Reflected in the response results 、 exception handling 、 The printing of logs should be under unified control .
Another is that you can use design patterns .
Design patterns 23 Kind of , Most commonly used, such as : The singleton pattern 、 The proxy pattern 、 Factory mode 、 Builder pattern 、 Template pattern 、 Strategy model, etc .
Spring Many design patterns are used in the source code , If you are interested, you can learn something about .
Readability
Readability is to provide convenience for future generations , It's the so-called iron camp, flowing soldiers .
When we write interfaces, we might as well add more comments to complex logic , This is not only convenient for others to read , Also bring yourself traversal .
边栏推荐
- Reinforcement learning - learning notes 3 | strategic learning
- 强化学习-学习笔记3 | 策略学习
- The solution of outputting 64 bits from printf format%lld of cross platform (32bit and 64bit)
- codeforces每日5题(均1700)-第五天
- MySQL index - extended data
- Video networkstate property
- Pytorch weight decay and dropout
- Pytorch MLP
- Flutter2 heavy release supports web and desktop applications
- Yolov5 target detection neural network -- calculation principle of loss function
猜你喜欢

Wireless WiFi learning 8-channel transmitting remote control module
![[deploy pytoch project through onnx using tensorrt]](/img/b6/ec95f028f749753666c7877134ad70.png)
[deploy pytoch project through onnx using tensorrt]

【TFLite, ONNX, CoreML, TensorRT Export】
![[yolov5.yaml parsing]](/img/ae/934f69206190848ec3da10edbeb59a.png)
[yolov5.yaml parsing]
Automated test lifecycle

Matlab struct function (structure array)

Network five whip
![[loss functions of L1, L2 and smooth L1]](/img/c6/27eab1175766b77d4f030b691670c0.png)
[loss functions of L1, L2 and smooth L1]

Liunx prohibit Ping explain the different usage of traceroute

Splunk configuration 163 mailbox alarm
随机推荐
查看rancher中debug端口信息,并做IDEA Remote Jvm Debug
Instance + source code = see through 128 traps
Uniapp + unicloud + Unipay realize wechat applet payment function
Hash tag usage in redis cluster
Vscode shortcut key
【ijkplayer】when i compile file “compile-ffmpeg.sh“ ,it show error “No such file or directory“.
MySQL trigger
GPS數據格式轉換[通俗易懂]
ABAP table lookup program
byte2String、string2Byte
ACID事务理论
强化学习-学习笔记3 | 策略学习
Learn memory management of JVM 01 - first memory
IPv6与IPv4的区别 网信办等三部推进IPv6规模部署
多表操作-子查询
Learn the memory management of JVM 03 - Method area and meta space of JVM
[HDU 2096] 小明A+B
Why do you always fail in automated tests?
mmclassification 训练自定义数据
A new WiFi option for smart home -- the application of simplewifi in wireless smart home