Quickly understand basic cookie, session and redis

1. Cookies

1. What is a cookie?

1. A cookie is actually a small piece of text information.Is a string of key=value form. The client requests the server, and if the server needs to record the user status, it uses the response to issue a cookie to the client browser. The client will save the cookie.
2. When the browser requests the website again, the browser submits the requested URL together with the cookie to the server. The server checks the cookie to identify the user status. The server can also modify the content of the cookie as needed.
3.The cookie only stores the user's identity, such as the userid represented by a string of strings; the server stores user information through the session, and then uses userid to find the corresponding user information.
4. Cookie is a mechanism for the client (browser) to store data. The key-value pair structure can store identity information and key information, all of which are customized by programmers. 5.
Cookie is a type provided by the browser. The ability for programmers to store data locally makes data more persistent on the client side.

2. Session Cookie and Persistent Cookie

1. Session cookie (memory cookie) :
If the expiration time is not set, it means that the lifetime of the cookie is during the browser session, and the cookie will disappear when the browser window is closed. This kind of cookie whose lifetime is the browser session is called a session cookie. Session cookies are generally not stored on the hard disk but stored in memory. Of course, this behavior is not specified by the specification.
2. Persistent Cookie (hard disk cookie) :
If an expiration time is set, the browser will save the cookie to the hard disk, and when the browser is closed and opened again, these cookies are still valid until the set expiration time is exceeded. Cookies stored on the hard drive can be shared between different browser processes. These are called persistent cookies.

3. Cookies cannot cross domain names

The cookie generated when you visit Bilibili will not be brought to CSDN's cookie.

4. How cookies work

The cookies stored in the browser come from the set-cookie field in the server's response "header". Each set-cookie field contains a key-value pair such as Cookie. After the browser gets the response, it will Save the content in the set-cookie locally, and the set-cookie is constructed and filled in by the programmer himself in the server.

insert image description here

Note:
1. Modify and delete cookies

  • If you want to modify the cookie, you can only use a cookie with the same name to overwrite the original cookie to achieve the purpose of modification.
  • When modifying or deleting a cookie, all attributes of the newly created cookie except value and maxAge, such as name, path, domain, etc., must be exactly the same as the original cookie. Otherwise, the browser will regard it as two different cookies and will not overwrite them, resulting in failure to modify and delete them.
  • When reading cookies from the client, other attributes including maxAge are unreadable and will not be submitted. When the browser submits the cookie, it only submits the name and value attributes. The maxAge attribute is only used by the browser to determine whether the cookie has expired.

2. Configure the domain name

  • The domain parameter must start with a dot ("."). In addition, cookies with the same name but different domains are two different cookies. If you want two websites with completely different domain names to share cookies, you can generate two cookies whose domain attributes are the two domain names and output them to the client.

3. Configure the path that allows access to cookies

  • When set to "/", all paths are allowed to use cookies. The path attribute needs to end with the symbol "/".

4. Configure the security attributes of cookies

  • The secure attribute does not encrypt the cookie content, so absolute security cannot be guaranteed. If high security is required, the cookie content needs to be encrypted and decrypted in the program to prevent leakage.
  • If you do not want cookies to be transmitted in non-secure protocols such as HTTP, you can set the secure attribute of cookies to true. Browsers only transmit such cookies on secure protocols like HTTPS and SSL.

2. Session

1. What is Session

1. Session is another mechanism for recording customer status , the difference isCookies are stored in the client browserAnd the Session is saved on the server. When the client browser accesses the server, the server records the client information on the server as a Session.
2. The session runs on the server side. When the client accesses the server for the first time, the user's login information can be saved; when the user accesses other interfaces, the session can be used to judge the user's login status and give a prompt.
3. Session is a mechanism for the server to store data. The key-value pair structure is mainly used forStore identity-related information

2. The working principle of Session

When Session calls getSession() or getSession(true), the bottom layer will automatically implement the Set-Cookie method, which means using
session will generate cookie to store JSESSIONID.
[getSession() or getSession(true) returns a key=value cookie key-value pair]

insert image description here

Note:
1, getSession(Boolean)

  • If the parameter is true , it will check whether there is a SessionId in the request, and whether the SessionId is legal.
    1. If there is a SessionId, it will find the corresponding HttpServlet object according to the SessionId (check the hash table), and organize several Sessions in the form of a hash table on the server side; 2. If there is no SessionId, the server
    will Generate a SessionId, create an HttpServlet object at the same time, insert this set of key-value pairs into the hash table of the Session managed by the server, and at the same timeReturn the sessionId to the client in the response through Set-cookie
  • If the parameter is false , it will also check whether there is a SessionId in the request and whether it is legal. If there is a SessionId, directly find the corresponding HttpServlet object and query all aspects of information.If there is no SessionId, the direct return is null

2. The way to save the session id

  • 1. Use cookies to save (default mechanism); 2. URL rewriting; 3. Form hidden fields

3. Session life cycle and validity period settings

  • Session is saved on the server side. In order to obtain higher access speed, the server generally puts the Session in memory. Each user will have an independent Session. If the session content is too complex, memory overflow may occur when a large number of clients access the server. therefore,The information in the Session should be as concise as possible
  • As more and more users access the server, there will be more and more sessions.To prevent memory overflow, the server will delete sessions that have not been active for a long time from memory. This time is the session timeout time. If the server has not been accessed after the timeout period, the Session will automatically expire.
  • Note: The unit of the <session-timeout> parameter is minutes, while the unit of setMaxInactiveInterval(int s) is seconds.

Doubt: Regarding the relationship between Session and Cookie
Answer: Cookie is stored on the client side; Cookie will be used when calling Session itself (working principle) . ).

3. The difference between Cookie and Session

1. The cookie data is stored on the client's browser, and the session data is stored on the server.
2. Cookies are not very secure. Others can analyze the cookies stored locally and perform cookie spoofing. Considering security, sessions should be used.
3. The session will be saved on the server within a certain period of time. When the number of visits increases, it will take up the performance of your server. Considering the reduction of server performance, cookies should be used.
4. The data saved by a single cookie cannot exceed 4K, and many browsers limit a site to save up to 20 cookies.
5. You can consider storing important information such as login information as a session. If you need to keep other information, you can put it in a cookie.

3. Redis

1. What is Redis

Redis (Remote Dictionary Server), that is, remote dictionary service, is an open source written in ANSI C language, supports the network, can be memory-based or persistent, log-type, Key-Value database, and provides APIs in multiple languages.

2. Why use Redis (Why should Session be used in combination with Redis)

In actual projects, it needs to be deployed on multiple servers to prevent excessive pressure on a certain server and avoid system performance problems or downtime.

eg1. For example (only use session and cookie)
For the login system, users mainly access our nginx proxy server request system.
If the user's first request is assigned to server A, the created Session object is in the memory of A, and the cookie returned to the user is JSESSIONID=abc123; the second time the user requests to use the cookie to find the session with the value of abc123, there is no need to do it again Logged in, but the second request is assigned to server B, and there is no abc123 in the memory of B, the request will fail, and the user has to enter the password again to log in, and the user experience is very poor.
insert image description here

eg2. For example (using redis to realize session sharing)
after joining redis, the session requested by the user for the first time is stored in Redis, even if the second request reaches server B, the corresponding session can be found from redis.
PS: I feel that Redis simply replaces each server to store sessions and realize sharing.
insert image description here

Why should Session be used in combination with Redis

  1. Distributed data storage
    Session data is stored in memory. If there is a cluster composed of multiple web servers, the session data will be scattered on each server, resulting in the inability to share the session data. The main function of Redis is to support distributed data storage, so it can solve this problem and share Session data on multiple web servers.
  2. High-performance
    Redis is a high-performance in-memory database that can handle a large number of read and write requests, greatly improving the reading and writing speed of Session data, thereby improving the performance of web applications.
  3. Support persistent storage
    Redis supports persisting data to disk to ensure that Session data will not be lost due to server downtime or shutdown. In this way, the security and reliability of user data can be guaranteed to the greatest extent.
  4. Support high concurrency
    Due to the high concurrency performance of Redis, it can support a large number of users to access web applications at the same time, thereby improving the processing capacity of the number of concurrent users and reducing the risk of bottlenecks in web applications.
  5. Powerful scalability
    Redis supports rich data structures and functions, and can expand and customize Session management functions as needed, making Session management more flexible and efficient.

3. Simple expansion

3.1 What is cache penetration? How to solve?

refers to both the cache and the databaseno data, causing all requests to fall to the database. The database collapsed due to a large number of requests in a short period of time.
insert image description here
Solutions:
1. The data that cannot be retrieved from the cache or the database can be set to key-null.
2. The Bloom filter hashes all possible data to a sufficient Go to the big bitmap (If it tells you that it exists, you can’t believe it all. In fact, it may not exist, but if it tells you that it does not exist, it must not exist)

3.2 What is cache breakdown? How to solve?

The same piece of data is queried with high concurrency , but the data in redis has expired. As a result, the request is sent to the database, causing a cache breakdown.
insert image description here
Solution:
1. Set the hotspot data to never expire;
2. Use a mutex. Use distributed locks in distributed cases

3.3 What is cache avalanche? How to solve?

If the cache fails in a large area at the same time , subsequent requests will fall to the database, causing the database to bear a large number of data requests in a short period of time. insert image description here
Solution:
The expiration time of cached data is set randomly to prevent a large amount of data from expiring at the same time.

3.4 Why is Redis query fast?

Although redis is a single-threaded program, because it is a pure memory database, it only operates memory (while our mysql is a hard disk operation), and uses asynchronous non-blocking IO (single thread + multiplexing IO model)

3.5 What is multiplexed IO?

When a request accesses redis, during the period of time when redis fetches data for this request, the entry of the request is not blocked, that is to say, the request can still be received until redis fetches the data, and then responds to these requests one by one.
Multiplexing: multiple socket connections, multiplexing: multiplexing one thread
Multiple I/O multiplexing technology allows a single thread to efficiently process multiple connection requests (minimize the time consumption of network IO).

3.6 Why is the single-thread query speed so fast?

First of all, it is certainly impossible for a single thread to be faster than multi-threaded, but the single-threaded mode avoids data concurrency security (because of multi-threaded data concurrency security, various locks appear). Then the advantages of our single thread come at this time: there is no need to consider the security of data concurrency, and there is no need for frequent thread scheduling and context switching.

3.7 What is context?

Every time a thread executes, it needs to read data from main memory into working memory. When the thread is blocked, the data in the working memory needs to be put into the thread context. In fact, the thread context is a storage structure. When the thread is woken up, it reads the content of the context, which is called context switching.

3.8 What are main memory and working memory?

Main Memory (Main Memory) is a hardware device used to store and access data inside a computer, usually referring to Random Access Memory (RAM). It is activated when the computer starts and runs until the computer is shut down. Main memory is usually where programs and data are stored, so it is also called program-level memory (Programmable Memory). In main memory, data is stored in memory cells, each with a unique address.

Working memory (Working Memory) usually refers to the cache area used by the thread (Thread) execution, also known as the thread's local memory (Thread Local Memory). Each thread has its own working memory. The thread's working memory stores its exclusive variable copy (Copy), and the variable copy in the working memory will be written back to the main memory after being manipulated. Shared data can be accessed between multiple threads. If a thread wants to access a shared variable, it will first copy the variable from the main memory to its own working memory, then operate on the variable, and finally write the value of the variable back to in main memory.

It should be noted that multiple threads cannot see the data stored in their respective working memory, and these data will only be transferred between their respective working memory and main memory. Therefore, in order to ensure data consistency between threads, Java provides some synchronization mechanisms, such as the synchronized keyword and the Lock interface. When a thread needs to access shared data, it needs to acquire a lock first to ensure that other threads cannot temporarily modify the data. before proceeding. These synchronization mechanisms ensure the visibility and consistency of data among multiple threads, avoiding data races and errors during concurrent access.

insert image description here

read (read): acts on the main memory variable, transfers a variable value from the main memory to the working memory of the thread, so that the subsequent load action uses
load (load): acts on the variable of the working memory, it transfers the read operation Variable values ​​obtained from main memory are placed into variable copies in working memory.
use (use): A variable that acts on the working memory, and passes a variable value in the working memory to the execution engine. This operation will be performed whenever the virtual machine encounters a bytecode instruction that needs to use the value of the variable.
Assign (assignment): Acts on the variable of the working memory, which assigns a value received from the execution engine to the variable of the working memory, and performs this operation whenever the virtual machine encounters a bytecode instruction that assigns a value to the variable.
store (storage): acts on the variable of the working memory, and transfers the value of a variable in the working memory to the main memory for subsequent write operations.
write (write): acts on a variable in main memory, which transfers the store operation from the value of a variable in working memory to a variable in main memory.

=====================================
This article refers to the following articles, and their descriptions are more detailed:

The difference between Cookie and Session Cookie and Session ( necessary
for interview)

[nodejs study notes] user login related: the use and advantages and disadvantages of cookie, session
and
redis
, redis)
Redis Detailed Explanation (Full)
Redis Detailed Explanation

Guess you like

Origin blog.csdn.net/weixin_42516475/article/details/130267821
Recommended