当前位置:网站首页>Detailed explanation of session mechanism and related applications of session

Detailed explanation of session mechanism and related applications of session

2022-06-22 19:21:00 Huangbao ~

session yes web An important concept in development , In most web In the application session They're all ready-made , Just use it , But there are some complicated problems web What can be used in the application session Has been unable to meet the actual needs , When faced with such a situation, we need a deeper understanding session The mechanism of , This article will sort out session Knowledge about , Is designed to replace web Self contained session The mechanism lays a foundation .

 

1.1 session The concept of

 

 

In computer terminology :session It refers to the time interval between an end user and an interactive system , It usually refers to the time elapsed between registering and logging off the system, and if necessary , There may still be some operating space .

 

Specific to the web Application in the session, Everybody did web Development , Here I will not put forward web in session The definition of , Let's talk to everyone first session Relevant technical background .

 

In the early web Applications or early websites are websites that deal with static resources , The main function is to view documents , Look at the pictures , Now the web The application is very different from the early stage , The more accurate definition of Internet website should be Internet software, that is, website is software , The definition of software represented by the website is different from that of early software , Early software was run in a stand-alone environment , The popularity of the Internet has brought software and network technology together , This requires that the software represented by the website should have a memory function for transaction processing , The memory function of transaction processing is what we often call statefulness . To achieve web The core of application technology http A protocol is a stateless protocol ,http This design may be a legacy of history , Perhaps stateless http Is the simplest and most effective means of communication , But when websites become software , State maintenance is a very important function .

 

So in web In application development, there is "keep" http Link state technology : One is cookie technology , The other is session technology .

 

cookie Technology is the solution for clients ( Of course as html5 Appearance , Than cookie More powerful and secure technologies have emerged , But whereas html5 The popularity of is not enough , I will not do the content discussed in this article ),Cookie This is the special information sent by the server to the client , And the information is stored in the client as a text file , Then every time the client sends a request to the server, it will bring these special information . Let's be more specific : When a user uses a browser to access a support Cookie When the website , The user will provide personal information including user name and submit it to the server ; next , The server will send back the personal information while sending back the corresponding hypertext to the client , Of course, this information is not stored in HTTP Response body (Response Body) Medium , But stored in HTTP Response head (Response Header); When the client browser receives a response from the server , The browser will store this information in a unified location , about Windows In terms of operating system , We can : [ System disk ]:\Documents and Settings\[ user name ]\Cookies The stored... Was found in the directory Cookie; Since then , When the client sends a request to the server again , Will put the corresponding Cookie Send back to the server again . This time, ,Cookie Information is stored in HTTP Request header (Request Header) 了 . With Cookie Such a technology realizes , After the server receives the request from the client browser , You can analyze the data stored in the request header Cookie Get client specific information , So as to dynamically generate the content corresponding to the client . Usually , We can see from the login interface of many websites “ Please remember me ” Such an option , If you check it and then log in , Then the next time you visit the website, you don't need to repeat and cumbersome login actions , And this function is through Cookie Realized .

 

session Technology is the solution of the server , It is maintained through the server . because Session This word contains a lot of semantics , So it needs to be clear here  Session The meaning of . First , We usually put Session Translate into conversation , Therefore, we can call a series of interactive actions between the client browser and the server a  Session. Starting from this semantics , We'll talk about Session The duration , It will be mentioned in Session What operations are carried out in the process, etc ; secondly ,Session It refers to the storage space opened up by the server for the client , The information stored in it is used to keep the State . Starting from this semantics , We will mention going to Session What is stored in , How to start from... According to the key value  Session Get the matching content in . To use Session, The first step, of course, is to create Session 了 . that Session When was it created ? Of course, it was created in the process of running the server-side program , Applications implemented in different languages are created differently Session Methods , And in the Java By calling HttpServletRequest Of getSession Method ( Use true As a parameter ) Created . In the creation of Session At the same time , The server will be Session Generate unique Session id, And this Session id It will be used in subsequent requests to retrieve the created Session; stay Session After being created , You can call Session Related methods Session Added to , And that content will only be stored on the server , Only Session id; When the client sends the request again , Will take this. Session id close , After the server receives the request, it will base on Session id Find the appropriate Session, So that it can be used again . Formalize such a process , The user's state is maintained .

 

From this we can conclude that ,session Is the solution http The server solution to the protocol stateless problem , It can make a series of interactive actions between client and server into a complete transaction , It can turn the website into a real software .

 

1.2 cookie And session The relationship between

cookie and session Although the solutions belong to the client and server respectively , But on the server side session The realization of is very important to the client cookie Having a dependency on , I talked about the server execution above session The mechanism will generate session Of id value , This id Values are sent to the client , Every time the client requests this id Values in http The request header is sent to the server , And this id Values will be saved on the client side , The container of preservation is cookie, So when we ban browsers completely cookie When , Server side session It will not work properly ( Be careful : Some sources say ASP Solve this problem , As a browser cookie It's banned , Server side session It can still be used normally ,ASP I haven't tried , But for many on the network php and jsp Write a website , I found it forbidden to cookie, Website session Can't access normally )

 

1.3 session Implementation principle

java Of web The containers are all implemented session Mechanism , The logical ideas of implementation are consistent , However, there may be some differences in the specific scheme , Here I use tomcat Container as an example , Discuss session The mechanism of implementation .

The picture below is tomcat Source code session Realization :

 

The path to the implementation package is :org.apache.catalina.session,tomcat External provision session The called interface is not in this implementation package , The external interface is in the package javax.servlet.http Under the HttpSession, And realize the... In the package StandardSession yes tomcat The standard implementation provided , Of course tomcat Do not want the user to operate directly StandardSession, It provides a StandardSessionFacade class ,tomcat Specific operations in the container session The components of are servlet, and servlet operation session It's through StandardSessionFacade On going , This prevents the programmer from working directly StandardSession The security problems caused by .(StandardSessionFacade It uses the design pattern Façade( appearance ) Pattern , Appearance pattern can decouple components of different logic layers ).

 

There are... In the implementation class Manager Class is used to manage session Tool class of , It is responsible for creating and destroying session object , among ManagerBase It's all session Base class of management tool class , It's an abstract class , All concrete implementations session All management function classes should inherit this class , This class has a protected method , This method is to create sessionId The method of value (tomcat Of session Of id The value generation mechanism is a random number plus time plus jvm Of id value ,jvm Of id The value will be calculated according to the hardware information of the server , So it's different jvm Of id Value is the only ),StandardManager Class is tomcat Default in the container session Manage implementation classes , It will be session Of information stored in web In the memory of the server where the container is located .PersistentManagerBase It's also inheritance ManagerBase class , It is all persistent storage session The base class of information ,PersistentManager Inherited PersistentManagerBase, But this class only has one more static variable and one more getName Method , It doesn't make much sense at present , For persistent storage session,tomcat It also provides StoreBase The abstract class of , It is all persistent storage session Base class of , in addition tomcat File storage is also provided FileStore And data storage JDBCStore Two implementations .

 

1.4  In practice session The problems brought about

As described above session Implementation mechanism , We will find that , To make up for it http The stateless nature of the protocol , The server will occupy a certain amount of memory and memory cpu To store and process session Computational overhead , This is the same. tomcat This one. web The concurrent connections of containers are so low (tomcat The default number of connections in the official document is 200) One of the reasons . So many java Language website , In the production environment web A static resource server will be added before the container , for example :apache Server or nginx The server , The static resource server is not resolved http The function of stateless problem , Therefore, servers that deploy static resources will not give up memory or cpu Computing resources are dedicated to dealing with things like session This function , These memories and cpu Resources can be more effective in handling each http request , Therefore, the number of concurrent connections to the static resource server is higher , So we can let those requests that do not have state retention requirements be processed directly in the static server , The request to maintain the state is in java Of web Dispose of in a container , This can better improve the efficiency of the website .

 

In order to improve website security and concurrency, the current Internet websites , The number of servers deployed on the server side is usually greater than or equal to two , The services provided by multiple servers are equivalent , But there must be different servers web Containers , From the above, we know session The implementation mechanisms of are web The internal mechanism in the container , This leads to a web Generated in the container session Of id The value is different , So when a request arrives A The server , When the browser gets a response , The client saves A Generated on the server session Of id, When another request is distributed to B The server ,B On the server web The container does not recognize this session Of id value , Not to mention this sessionID The corresponding recorded information , At this time, two differences are needed web Between containers session Synchronization of .Tomcat An official solution for containers is to use apache+tomcat+mod_jk programme , When one web In the container session After the information changes , The web The container will move to another web The container broadcasts , the other one web After receiving the broadcast, you will session The information is synchronized into its own container , This process consumes a lot of system resources , When the number of visits increases, it will seriously affect the efficiency and stability of the website .

 

There is a solution in the website I am working on , When users request a website, they will first send the request to the hardware load balancing device , The device can intercept the messages sent by the client session Of id value , And then we start with this id Value found produces this session Server for , Send the request directly to this server . This solution seems to solve session Sharing issues , In fact, the result is that the cluster system is finally changed back to a single point system , If the request is processed web The container hung up , Then the user's related session operations will be invalidated . Besides , This practice also interferes with the load balancing calculation of the load balancing server , Let the distribution of requests be unfair .

 

   Generally, the websites of large Internet companies are composed of independent channels , For example, we often use Baidu , There will be Baidu search , Baidu Music , Baidu Encyclopedia and so on , I believe they will not give these different channels to a development team , Each channel should be an independent development team , Because the application of each channel is independent web application , Then there is a cross site session Synchronization issues , Cross site login can use single sign on (SSO) Solutions for , But whatever the solution , Cross site session Sharing is still an unavoidable problem .

 

1.5  solve session Technical solutions for related problems

As mentioned above ,session There are two problems to be solved :

1) session Your storage should be independent of web Containers , Also be independent of deployment web Container's server ;

2) How to conduct efficient session Sync .

Before we talk about solving these problems , We must first consider session How to store is efficient , There is memory 、 The file is still a database ? Both files and databases are stored in a way that session Data is solidified on the hard disk , The way to operate a hard disk is IO,IO The efficiency of the operation is much lower than that of the operation of the data in memory , Therefore, it is not advisable to store files and databases , So will session Storing data in memory is the best choice . So the best solution is to use distributed caching technology , for example :memcached and redis, take session Independent storage of information is also a solution session Method of synchronization problem .

Tomcat Of session Synchronization is also used memcache Solutions for , You can join the following article :

 

  http://blog.sina.com.cn/s/blog_5376c71901017bqx.html

But this solution only solves the synchronization problem ,session Mechanism still and web The container is tightly coupled , We need an efficient 、 Scalable solutions , Then we should not simply put session Independent storage, but design a completely independent session Mechanism , It can give everyone web Application provide session The function of can be realized session Sync , The following is an article with zookeeper Distributed implementation session programme :

 

http://www.open-open.com/lib/view/open1378556537303.html

 

OK, that's it , Today is just a simple analysis session Mechanism , In the future, I will come up with the best set of independent session Design mechanism scheme .

原网站

版权声明
本文为[Huangbao ~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221750419918.html