About the author
Yesterday, I posted this article on Sifu, and I saw a lot of likes, favorites and attention at 10 PM. Actually, I felt quite guilty, because I haven’t finished sorting out this article when I am looking for a job recently. It is very welcome to see this, but also because the new job has been basically settled. Now the company is in normal transition, and WE plan to sort out this knowledge by the end of next week. Thank you for your likes, favorites and attention.
Also, my own blog site is here, haha: www.linganmin.cn
Algorithms and data structures
BTree and B + tree
- BTree
A B-tree is a multi-fork balanced search tree designed for disks or other storage devices. Compared with a binary tree, each inner node of a B-tree has multiple branches, that is, multi-forks.Reference article: www.jianshu.com/p/da5…
- B+Tree
The B+ tree is a variant of the B tree and a multipath search tree.Reference article: www.jianshu.com/p/da5…
Sorting algorithm
-
Quicksort quicksort is a very common efficient algorithm, the idea is: first choose a ruler, with it the entire queue through a screening, to ensure that the left elements are not larger than it, its right elements are not small with it
$arr = count($arr); $arr = count($arr); If ($length <= 1){return $arr; } // define the base element $base = $arr[0]; $left = []; $left = []; $right = []; For ($I =1; $i < $length; $i++) {/ / and a benchmark to compare the if ($arr ($I) > $base) {$right [] = $arr ($I); }else { $left[] = $arr[$i]; $left = quickSort($left); $right = quickSort($right); Return array_merge($left,[$base],$right); }Copy the code
-
2,4, 1:4:2 on the first attempt, 1:4 on the second attempt, 2:1, 2:4, 4 on the second attempt
Function bubbleSort($arr){$length = count($arr); For ($I =0; $i < $length-1; $i++) {// the inner loop controls the number from the 0th key to the next key, each time a maximum number for ($k=0; $k < $length-$i; $k++) { if($arr[$k] > $arr[$k+1]){ $tmp = $arr[$k+1]; $arr[$k+1] = $arr[$k]; $arr[$k] = $tmp; } } } return $arr; }Copy the code
-
Select the sorting idea: select the corresponding element one at a time and place it in the specified position
Function selectSort($arr){return $length = count($arr); for ($i=0; $i < $length - 1; $I ++) {$p = $I; For ($j=$I +1; $j < $length; If ($arr[$p] > $arr[$j]) {$p = $j; if ($arr[$p] > $j) {$p = $j; If ($p! = $p! = $p! = $p! = $p! = $p! = $p! = $p! = $p! = $i) { $tmp = $arr[$p]; $arr[$p] = $arr[$i]; $arr[$i] = $tmp; Return $arr; }Copy the code
Computer network
TCP/UDP
- TCP TCP is a connection-oriented, reliable, and byte stream based transport layer communication protocol. TCP Connection-oriented, providing reliable data services. TCP header overhead 20 bytes TCP logical communication channels are full-duplex reliable channels
- UDP UDP is a connectionless transport layer protocol in the reference model, providing a simple and unreliable transaction oriented information transfer service UDP connectionless, unreliable UDP header overhead 8 bytes UDP logical communication channel is an unreliable channel UDP has no congestion mechanism. Therefore, network congestion does not reduce the sending efficiency of the source host. UDP supports one-to-one, many-to-one, and many-to-many communication
Three handshakes, four waves. Why three handshakes, four waves
In THE TCP/IP protocol,TCP provides reliable connection service. A three-way handshake is used to establish a connection. After the three-way handshake is completed, the client and server begin to transmit data. In simple terms, when A establishes A TCP connection with B, A sends A SYN (synchronous request) to B, and B replies with A SYN+ACK (synchronous request). Finally, A replies with an ACK confirming the TCP connection.
-
TCP three-way handshake
A three-way handshake is a TCP connection that requires the client and server to send a total of three packets
The purpose of the three-way handshake is to connect to the specified port of the server, resume the TCP connection, synchronize the serial number of the connected parties, and exchange TCP window size information.
TCP three-way handshake
- The first handshake client sends a TCP PACKET with the SYN flag at position 1, indicating the port of the server to which the client intends to connect, and the initialization sequence number, stored in the sequence number field of the packet header
- For the second handshake, the server responds with an acknowledgement packet, that is, the SYN flag and ACK flag are both 1, and the ISN of the customer is set to 1, that is, X+1
- For the third handshake, the client sends an acknowledgement packet with the SYN identifier 0 and ACK identifier 1. The client sends the sequence number field +1 in the CONFIRM field and writes the ISN +1 in the data field
The TCP three-way handshake is as follows: github.com/jawil/blog….
-
Four times to wave
The removal of a TCP connection requires four packets to be sent, hence the quadruple wave. The client or server can initiate the wave action.
Because TCP connections are full-duplex, each direction must be closed separately. The principle is that a party can send a FIN to terminate the connection in that direction when it has completed its data transmission task. Receiving a FIN only means that there is no data flow in that direction, and a TCP connection can still send data after receiving a FIN. The party that closes first performs an active shutdown and the other party performs a passive shutdown. - This is because the socket in LISTEN state on the server can send ACK and SYN in one packet after receiving the resume connection request of the SKY packet. However, when you close the connection and receive a FIN packet notification from the peer, it only indicates that the peer has no data to send to you. However, all data may not be sent to the peer. Therefore, you can close the socket immediately, that is, you may send some data to the peer. You agree to close the connection by sending a FIN packet to the peer, so ACK and FIN packets are usually sent separately.
Long connection and short connection
TCP before really read and write operations, must establish a connection between server and client, when after the completion of the read and write operations, the two sides are no longer needed the link they may release the connection, the connection is built by three times handshake, release requires four wave, so the establishment of each connection is need to consume resources and time.
-
TCP short connection
- The client sends a connection request to the server
- The server receives the request and establishes a connection
- The client sends messages to the server
- The server response to the client
- When the read/write operation is complete, either of the two parties can initiate the close operation. Usually, the client initiates the close operation first, because the server does not immediately close the connection after replying to the client
Therefore, a short connection transmits only one read/write operation between the client and server. It is easy to manage short connections. All existing connections are useful connections and no additional control is required
-
A long connection
- The client initiates a connection to the server
- After the server receives the request, the two parties establish a connection
- The client sends messages to the server
- The server response to the client
- Once read and write, the connection is not closed
- Subsequent read and write operations
-
Operation procedure of long/short connection
- Procedure for short connection: Establish connection -> Data transfer -> Close connection
- Procedure for long connection: Establish connection -> Data Transfer -> (Keep connection) -> Data transfer -> Close connection
-
Advantages and disadvantages of long/short connections
- Long connections save TCP establishment and closure operations, waste resources, and save time. Long connections are suitable for clients that frequently request resources
- Short connections are easy to manage for the server. All existing connections are useful connections, and no additional control is required
What happens from the time the browser enters the domain name to the display page
- For DNS domain name resolution, check the hosts file on the local PC and the IP address of the corresponding domain name. If a DNS server sends a request to the IP address, it does not go to the DNS server
- Establish TCP connection to get the server IP, send to the server beg, three times shake hands, establish TCP connection simple understanding three times shake hands: client: hello, at home no, have you express server: in, send client: good drop, come
- Sending AN HTTP request After establishing a connection with the server, you can send a request to the server. You can view the specific request content in the browser
- Server processing request to the server after receipt of a request by the web server (Apache, Nginx) handle the request, a web server parse user requests, know that you need to call the resource file, and then by the corresponding these resource file handling user requests and parameters, and call the database and so on, and then the results through the web server returns to the browser
- Return the response result. In the response result, there is an HTTP status code, such as 200, 404, and 500, which are composed of three digits and a reason phrase. There are five types of status codes: 1XX Informational status code The received request is being processed 2XX success status code The request is processed properly 3XX Redirection status code Additional operations are required to complete the request 4XX client error status code The server cannot process the request 5XX server error status code The server fails to process the request
- Closing a TCP connection To avoid resource consumption on both the server and client, either of the two parties can initiate the closing request when no request or response is received. Similar to the three-way handshake for creating a TCP connection, closing a TCP connection requires four waves of the hand. Server: Ok, I have no data to send to you. No server: Brother, I have no data to send to you. We can close the connection to client: Ok
- Browser parsing HTML
- Browser Layout rendering
Design patterns
A design pattern is a set of repeated, well-known, catalogued code design lessons. Design patterns are used to re-use code, make it easier for others to understand, and ensure code reliability.
The singleton pattern
The singleton pattern is useful when you need to ensure that there is only one instance of an object. He gives control of creating objects to a single point, and there is only one instance of the application at any one time. Singleton classes should not be instantiated outside the class. A singleton class should have the following factors:
- Must have an access level of
private
Constructor to prevent classes from being arbitrarily instantiated - You must have a static variable that holds an instance of the class
- You must have a public static method that accesses this instance, usually named
getInstance()
- Must have a private empty
clone
Method to prevent instances from being cloned
A simple example:
class Single { public static $_instance; private function __construct() { } private function __clone() { } public static function getInstance() { if (! self::$_instance) { self::$_instance = new self(); } return self::$_instance; } public function sayHi() { echo "Hi \n"; } } $single = Single::getInstance(); $single->sayHi();Copy the code
The factory pattern
The factory pattern addresses how to create instance objects without new
The factory pattern is a class that has certain methods for creating objects for you that you can use without using the factory class
new
. That way, if you want to change the type of object you create, all you need to do is change the factory, and all the code that uses that factory will change automatically.
The factory pattern is often used in conjunction with interfaces, so that applications do not need to know the details of the classes being instantiated, but can be easily used knowing that the factory returns a class that supports an interface.
A simple example:
Public function showInfo(); public function showInfo(); Class Student implements Person {public function showInfo() {echo "this is a Student \n"; Class Teacher implements Person {public function showInfo() {echo "Class Teacher implements Person () {echo \n"; Public static function factory($person_type) {public static function factory($person_type) {// Capitalize the first letter of the incoming type $class_name = ucFirst ($person_type); if(class_exists($class_name)){ return new $class_name; }else{throw new Exception(" class: $class_name does not exist ",1); $student = PersonFactory::factory('student'); echo $student->showInfo(); $teacher = PersonFactory::factory('teacher'); echo $teacher->showInfo();Copy the code
Cache related
The difference between Redis and Memcached
- Both Redis and Memcache store data in memory. Both are in-memory databases. But Memcache can also cache other things, like pictures and videos
- Redis not only supports simple K/V type data, but also provides the storage of list, set, hash and other data structures
- Virtual memory. When the physical memory runs out, Redis can swap some values that have not been used for a long time to disk
- Expiration policy, memcache specifies when set, for example
set key1 0 0 8
Redis can be set with expire, for example:expire name 10
- Distributed, set memcache cluster, using Magent to do a master and multiple slave; Redis can also do many things.
- Storage security, memcache down, data is lost; Redis can be saved to disk periodically (persistent)
- In disaster recovery, data cannot be recovered after memcache is down. Lost redis data can be recovered through AOF
- Redis supports data backup, namely, data backup in master-slave mode
- Different application scenarios: Redis can not only do NOSQL database, but also can do message queue, data stack and data cache. Memcache is suitable for caching SQL statements, data sets, temporary user data, deferred query data, and sessions
What data structures redis has
-
String is the most basic data structure of Redis. The key is a String, and the other structures are built on the basis of the String type.
- The most classic use scenario of cache string is redis as the cache layer and mysql as the storage layer. Most of the requested data is obtained from Redis. Because Redis supports high concurrency, cache usually plays a role in accelerating read and write and reducing back-end pressure
- Counter Many applications will use Redis as the basic tool of technology, it can realize the function of fast technology, query cache.
- In consideration of load balancing, distributed services will balance user information access to different servers, and users may have to log in again if they refresh their access. In order to avoid this problem, redis can be used to centrally manage user sessions. In this mode, as long as the high availability and expansibility of Redis are guaranteed, Every time you retrieve user updates or query login information, it is centrally fetched directly from Redis
- Rate Limit For security purposes, users are required to enter verification codes for each login. To prevent frequent access to the SMS interface, users are limited in obtaining verification codes every minute
-
Hash in Redis, Hash means that the key itself is a key-value pair structure, for example,value = {{field1,value1}… {fieldn,valuen}}
- The hash structure is more intuitive than string serialization cache information and is easier to update.
-
The list type is used to store multiple ordered strings. Each string in the list becomes an element. A list can store up to 2 ^ 32 minus 1 element. In Redis, you can insert (push) and pop (pop) lists, and you can get lists of elements in a specified range. Lists are flexible data structures that can act as stacks and queues. Usage Scenarios:
- The message queue
The redislpush+brpop
Command combination can be implemented blocking queues, producer client is usedlpush
Insert elements from the left side of the list for use by multiple consumer clientsbrpop
Command blocking grabs elements at the end of the list, and multiple clients ensure high availability of consuming load balancing. -
Using tips list
Lpush + RPOP =Stack lPUSH + RPOP =Queue Lpush + LTRIM =Capped Collection lPUSH + BRPOP =Message QueueCopy the code
- The message queue
- set
- sortedset
Is Redis single threaded and why
Since CPU is not the bottleneck of Redis, the bottleneck of Redis is most likely machine memory or network bandwidth. Since a single thread is easy to implement and the CPU is not a bottleneck, it makes sense to adopt a single thread solution.
Of course a single Redis process cannot use multiple cores, but it is not a very computationally intensive service. If single-core performance is not enough, you can open more processes.
Redis deployment mode: primary/secondary, cluster
Reference article: segmentfault.com/a/11…
Redis sentinel mode
Reference article: www.cnblogs.com/xifen…
Redis persistence strategy
- RDB (Snapshot Persistence)
- AOF(Append file persistence only)
Reference article: segmentfault.com/a/11…
PHP based
-
Double quotation marks Single quotation marks are different
- Double quotation marks explain variables, single quotation marks do not
- Insert single quotation marks inside double quotation marks, where variables, if any, are explained
- The variable name in double quotation marks must contain special characters other than digits, letters, and underscores (_), or use {} to enclose variables. Otherwise, the parts following the variable name will be considered as a whole, causing syntax errors
- Enable single quotation marks to be used as much as possible. Single quotation marks are more efficient than double quotation marks
-
The difference between GET and POST submissions
- GET generates a TCP packet; POST generates two TCP packets; For GET requests, the browser sends both HTTP headers and data, and the server responds with 200 (return data). For POST, the browser sends the header, the server responds with 100 continue, and the browser sends data, The server responds with 200 OK (return data).
- GET is harmless when the browser falls back, while POST resubmits the request
- GET requests are actively cached by browsers, whereas POST requests are not, unless set manually
- GET request parameters are retained in browser history, while parameters in POST are not
- GET requests can only be url encoded, while POST supports multiple encoding methods
- GET is less secure than POST because parameters are exposed directly to the URL and therefore cannot be used to pass sensitive information
- How do I obtain the real IP address of a client
$_SERVER [‘ REMOTE_ADDR] or getenv (” REMOTE_ADDR “)
You can useip2long()
To digital - Include and require
Require is an unconditional inclusion, which means that if require is added to a process, it will execute require first regardless of whether the condition is true or not. If the file does not exist or cannot be opened, an error will be given and the program execution will be terminated
Include has a return value, whereas require does not (perhaps because require is faster than include). If the included file does not exist, an error is raised, but the program continues to executeNote: require is fatal if the include file does not exist or is syntactically incorrect, but include is not
- What are the advantages of AJAX? AJAX is an asynchronous transfer technology, which can be implemented through javascript or JQuery framework to achieve local refreshes, reducing server stress and improving user experience
-
In the program development, how to improve the efficiency of the program
- Optimize SQL statements, try not to use SELECT * in query statements, which field to check which field;
- Use less subqueries instead of table joins;
- Use less fuzzy query;
- Create index in data table;
- Generate a cache of frequently used data in the program;
-
The difference between SESSION and COOKIE
- Storage location: The session is stored in the server, and the cookie is stored in the browser
- Security: Session security over Cookie Reference link: www.zhihu.com/questio…
-
Isset and Empty
- The isset() function is used to check whether a variable isset and returns FALSE if it does not exist and its value is NULL if it does and its value is not NULL, then returns true
- Empty () checks if the variable is empty and returns TRUE if it does not exist. If it does exist and its value is “”, 0, “0”, NULL, FALSE, array(), var $var; Return true if the variable exists and the value is not “”, 0, “0”, NULL, FALSE, array(), var $var; And objects that do not have any attributes, return FALSE
-
Database three paradigm
- The first normal form: 1NF is the atomicity constraint on attributes, which requires attributes to have atomicity and cannot be decomposed again.
- Second normal form: 2NF is a constraint on the uniqueness of records, requiring records to have a unique identity, that is, the uniqueness of entities;
- Third normal Form: 3NF is a constraint on field redundancy, that is, no field can be derived from any other field, which requires that the field have no redundancy.
-
Differences between primary keys, foreign keys, and indexes
- The foreign key of a table is the primary key of another table. The foreign key can have a duplicate or a null value index. This field has no duplicate value, but it can have a null value
- Primary keys – used to ensure data integrity – indexes used to establish relationships with other tables – are used to speed query sorting
- Number of primary keys – primary keys can have only one foreign key – a table can have multiple foreign key indexes – a table can have multiple unique indexes
- Stack is the memory allocated at compile time, so your code must have a clear definition of the stack size; The heap is the amount of memory allocated dynamically while the program is running. You can determine the size of the heap to allocate based on how the program is running.
PHP package manager Composer with autoloading specification
Composer learn address: docs.phpcomposer.com/0…
Automatically load mappings in composer. Json
Currently, pSR-0 autoloading, PSR-4 autoloading, ClassMap generation and files import are all supported, with PSR-4 being the preferred method because it provides greater ease of use.
-
Psr-4 specifies how to specify file paths to automatically load classes, as well as where to automatically load files. At first glance this looks like a repeat of the PSR-0, but in fact, there is some duplication in functionality. The difference is that the PSR-4 specification is cleaner, removing compatibility with pre-PHP5.3 versions. The biggest difference between PSR-4 and PSR-0 is the definition of underscores. In PSR-4, underscores have no special meaning in class names, while in PSR-0, underscores are converted to directory separators
Under the key of PSR-4, you can define the mapping between namespaces and paths. When autoloading a class like Foo\\Bar\\Baz, namespace Foo pointing to a directory named SRC/means that the autoloader will look for a file named SRC /Bar/ baz.php and reference it.
Namespace prefixes must end with \\ to avoid conflicts between similar prefixes. During installation and update, the PSR-4 references are all combined into a key=>value array, which can be found in the generated file vendor/ Composer /autoload_psr4.php.
Example:
{" autoload ": {" PSR - 4" : {" App \ \ ":" App/App / / namespace mapping to the directory App}}}Copy the code
-
Classmap All combinations referenced by classmap are generated during installation and update and stored in the vendor/ Composer /autoload_classmap.php file. You can use classMap to generate custom loaded libraries that do not conform to the PSR-4 specification. Configure the directory to point to so that class files can be searched accurately
Example:
{ "autoload": { "classmap": ["src/", "lib/", "Something.php"] } }Copy the code
-
Files If you want to specify explicitly that certain Files are to be loaded on each request, you can use the Files field to load. Usually used as a loading method for function libraries.
Example:
{ "autoload": { "files": ["src/MyLibrary/functions"] } }Copy the code
PHP framework
Laravel related
The front-end related
JavaScript
VueJS
- VueJs bidirectional data binding principle
Linux
Cors cross-domain
The basic principle of CORS is to tell the browser that the HTTP request is valid by setting the header in the HTTP request and returning it. This involves setting both the server side and the browser side: the initiation of the Request (Http Request Header) and the correct response of the server to the Request (Http response Header).
Reference article: zhuanlan.zhihu.com/p/…