How is Session implemented? Where is it stored?

content

foreword

  The content of the article is reproduced or excerpted from, the following article. Finally, at the end of the article [Blogger's Note], I will point out some points that need attention.

Why is there a session?

  First of all, everyone knows that the http protocol is stateless, that is, if you visit a web page 100 times in a row and visit once, there is no difference for the server, because it can't remember you. 
  So, in some occasions, what if the server really needs to remember the current user? For example, after a user logs in to the mailbox, they need to receive and write emails. It is impossible to ask the user to enter the user name and password for each operation. In order to solve this problem, the session solution was proposed. In fact, it is not new. technology, but also cannot be separated from the http protocol and any existing web technology. 
  The principle is very simple. Suppose when you visit the web page, it is like visiting a bathroom. You don’t have a key when you enter the website for the first time. At this time, when you pay the money, the service desk will assign you a key. You have to take it with you wherever you go, because This is the only identification of your identity. Next, you can use this key to open a special locker to store your clothes. After swimming, you can use the key to open the locker and take out clothes. When you finally leave the swimming pool, Return the key, your swimming process is a session, or a session. In this example, the key is the key of the session, and the locker can be understood as a medium for storing user session information. 
  So how to implement session in web server? It must be easy to understand after reading the above example, mainly to solve two problems, one is the problem of keys, and the other is the problem of storing user information. For the first question, what is it that you can automatically bring to the server every time you request it? If you are familiar with the http protocol, then the answer is clear at a glance. It is a cookie. If you want to establish a session for a user, you can give him a cookie when the user is successfully authorized. It is called session id, which is of course unique. For example, PHP will create a session for the user. The user of the session sets a cookie named phpsessid by default, and the value looks like a random string. If it finds that the user has brought this cookie next time, the server will know that, oh, the customer just came. 
  What remains is to solve the second problem, that is, how to store the user's information. The server knows that the user whose session id is abc is coming. How should abc want to store its own private information, such as shopping cart information? At this time, you can use memory, files, or databases, but there is a requirement that the data can be obtained by using the user's session id. For example, php will store the user session data whose session id is abc by default. In the file of /tmp/phpsess_abc[1], each time it is read, the data that the program can understand must be deserialized, and when it is written, it needs to be serialized into a persistent data format.

How to achieve session sharing?

  First of all, we should understand why sharing is needed. If your website is stored on one machine, then this problem does not exist, because the session data is on this machine, but if you use load balancing to distribute requests to different machine? At this time, there is no problem with the session id on the client side, but if the user's two requests are sent to two different machines, and its session data may exist on one of the machines, the situation that the session data cannot be obtained will occur at this time. , so session sharing becomes a problem. 
  In fact, various web frameworks have already considered this problem, such as asp.NET, which supports modifying the session storage medium through configuration files to sql server. The session data of all machines is read from the same database, so there will be no inconsistency. php supports storing session data to a memcache server , you can also manually change the directory where session files are stored to the nfs network file system, so as to achieve cross-machine sharing of files. 
  There is also a simple method that can be used when the session information does not change frequently. When the user session is set on machine a, the session data is posted to a cgi of machine b, and the cgi of machine b saves the session data, so that the machine Both a and b will have a copy of the same session data. 【2】  

Where is the SESSION data stored?

session storage in PHP

  Where is the SESSION data stored? 
  On the server side of course, but not in memory, but in a file or database. 
   By default, the SESSION saving method set in PHP.ini is files( session.save_handler = files), that is, SESSION data is saved by reading and writing files, and the directory where the SESSION file is saved is  session.save_path specified. The file name is prefixed with sess_, followed by the SESSION ID, such as : sess_c72665af28a8b14c0fe11afe3b59b51b. The data in the file is the serialized SESSION data. 
   If the amount of access is large, there may be more SESSION files. At this time, you can set the hierarchical directory to save the SESSION files, and the efficiency will be improved a lot. The setting method is: session.save_path="N;/save_path", N is the number of hierarchical levels, and save_path is the start directory. 
   When writing SESSION data, php will get the SESSION_ID of the client, and then find the corresponding SESSION file in the specified SESSION file storage directory according to the SESSION ID, create it if it does not exist, and finally write the data to the file after serialization 【3】. Reading SESSION data is also a similar operation process. The read data needs to be deserialized to generate corresponding SESSION variables.

Session storage in Java

  Sessionid is the key of a session. When the browser accesses the server for the first time, a session will be generated on the server side, and there is a sessionid corresponding to it. The sessionid generated by tomcat is called jsessionid. 
  The session is created when accessing the getSession(true) of the HttpServletRequest of the tomcat server. The ManagerBase class of tomcat provides a method for creating sessionid: random number + time + jvmid. 
  Stored in the memory of the server, the StandardManager class of tomcat stores the session in the memory, and can also be persisted to file, database, memcache, redis, etc. The client only saves the sessionid in the cookie, but does not save the session. The session can only be destroyed by invalidate or timeout. Closing the browser will not close the session.


  So when is the Session created? Of course, it is created during the running of the server-side program. Applications implemented in different languages ​​have different methods of creating a Session. In Java, they are created by calling the getSession method of HttpServletRequest (using true as a parameter). [4] When the Session is created, the server will generate a unique Session id for the Session, and this Session id will be used to retrieve the created Session in subsequent requests; after the Session is created, you can call Session-related methods add content to the Session, and these content will only be stored in the server, and only the Session id will be sent to the client; when the client sends a request again, it will bring the Session id, and the server accepts the request. After that, the corresponding Session will be found according to the Session id and used again.


  Create: The sessionid is generated for the first time until a server-side program calls a statement such as HttpServletRequest.getSession(true). 
  Delete: timeout; program calls HttpSession.invalidate(); program closes. 
  Where the session is stored: in memory on the server side. [5] However, sessions can be persistently managed in a special way (memcache, redis). 
  Where does the session ID come from, and how is the session ID used: When the client requests the session object for the first time, the server will create a session for the client, and will calculate a session ID through a special algorithm to identify the session session object. 
  Will the session be deleted because the browser is closed? No, the session will only be closed by the method mentioned above. 【6】

Bloggers Note

[1] It needs to be explained here. The blogger found in wamp under Windows that there is a tmp directory in the wamp installation directory, and the files saved by session data are named with "sess_" as the prefix. In the nginx+php-fpm environment in CentOS, after configuring the save path of the session (configure the value of session.save_path in php.ini, note that this path requires the user to which the web server process belongs to have the right to operate - read and write operations ), the saved Session files are also named with the prefix "sess_". 
[2] In addition to the methods mentioned above, there is another way to solve the problem of session sharing: (in essence, it is not solved by session sharing) Here, taking nginx as an example, user requests are distributed to different machines. Then we only need to fix that the same user request is distributed to the same machine for processing, that is, this time the user requests the server, then the next time it comes again, the request is also distributed to the same server as the last time. This ensures that the same user will not be unable to obtain session data because the request is distributed to different machines. 
[3] The background server can save the data in the session. For php, the data is serialized and saved in the file. The content is as follows:

USER|a:5:{s:7:"user_id";s:6:"512071";s:8:"username";s:18:"未命名的昵称";s:5:"phone";s:11:"18888888888";s:9:"last_time";s:19:"2017-06-30 15:45:55";s:6:"is_vip";s:1:"0";}noLoginUser|a:2:{s:10:"session_id";s:40:"captcha_81cd8166e5a84a56605c5903466416da";s:11:"verify_code";s:4:"9626";}
  • 1

【4】Open the browser to visit a certain website, close the browser. We count such an operation as a "session". Therefore, most people think that a session ID will be generated when a user visits a website. Actually not. For example: in Java we need to call the getSession method of HttpServletRequest to create a session. In PHP, it takes a while for the session_start()server to send back the cookie with the session ID. Otherwise, no session will be generated. 
[5] "Where is the session stored: in the server-side memory." refers to the way Tomcat saves the session. For PHP it is stored in a file. mentioned above. 
[6] The session will not be deleted due to the closing of the browser. But the default expiration time for cookies with session IDs is session level. That is, when the user closes the browser, the session ID stored on the client side will be lost, but the session data stored on the server side will not be deleted immediately. From the client's point of view, the browser, it seems that the session has been deleted (because we lost the session ID and can't find the original session data).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324758835&siteId=291194637