“This article has participated in the call for good writing activities, click to view: the back end, the big front end double track submission, 20,000 yuan prize pool waiting for you to challenge”

I am Chen PI, an ITer of Internet Coding. I search “Chen PI’s JavaLib” on wechat and read the latest articles as soon as possible, reply to [information], and then I can get the technical materials, electronic books, interview materials of first-line big factories and excellent resume templates carefully arranged by me.

preface

As we know, HTTP is a stateless protocol, and the server does not know which request was initiated by which user. In some scenarios we need to know which user initiated the request and which user acted on it. For example, the mall service, the user initiates a request to place an order, the server needs to identify which specific user. So the server needs to use some mechanism to identify, record user information, status, etc.

This can be achieved through the Session mechanism, which makes HTTP stateful for stateless protocols. The server creates a unique Session for each user requesting the server to identify and track the user. The Session is stored on the server, can be stored in files, memory, data, etc., and has a unique ID that identifies the Session. After a Session is created, the server tells the client through HTTP to record the Session ID in the local Cookie. In this way, each subsequent request from the same client will be sent to the server together with the Cookie. The server can check the Session ID stored in the Cookie to know which user is requested this time.

Session

Session in Chinese means Session. The session state of one-to-one interaction between a client and a server is an abstract concept. Many people think of Session as the Session object obtained by the following code. In fact, this is just a generic implementation of cookies. There are many different implementations of sessions.

 HttpSession session = request.getSession();
Copy the code

Because most applications use cookies to implement Session tracking, that’s the line above. Cookies actually exist. When the client requests the server and creates a Session for the first time, the server tells the client through the HTTP protocol (set-cookie in the HTTP response header) that the Session ID needs to be recorded in the local Cookie. The value of key is JSESSIONID.

In this way, each subsequent request from the same client will be sent to the server together with the Cookie. The server can check the Session ID stored in the Cookie to know which user is requested this time.

 HttpSession session = request.getSession();
Copy the code

However, cookies can be disabled by the client browser, which can cause problems. However, we can use URL rewriting technology to achieve Session tracking, that is, to add a representative user ID or Session ID to all request parameters on the request server side.

 http://chenpi.com/list?sid=xxx
Copy the code

We’ve already said that sessions can be stored in files, memory, databases, etc. In fact, the specific storage location of session information depends on its own business. Any talk about technical architecture without business scenarios is hooliganism. Technology itself is not good or bad, but what business scenarios are suitable for what technologies, which is also the ability of architects to consider technology selection.

However, Session consistency needs to be considered in the cluster service. Session synchronization can be performed in a cluster service, but this method has some disadvantages, such as cumbersome synchronization, synchronization delay, and the waste of storage space when storing the same Session on multiple machines. Another commonly used method is to use a special Session service cluster to store user Session information, such as Redis cache service, which can not only build a cluster mode to achieve high availability and expansion, but also achieve high speed based on memory performance.

public UserContext getUserContext(HttpServletRequest request) { String userToken = getUserToken(request, COOKIE_KEY); if (! StringUtils.isEmpty(userToken)) { String userContextStr = redisUtils.getString(RedisKeyUtil.genKey(userToken)); if (! StringUtils.isEmpty(userContextStr)) { return JSON.parseObject(userContextStr, UserContext.class); } } return null; } public String getUserToken(HttpServletRequest request, String cookieName) { Cookie[] cookies = request.getCookies(); if (null ! = cookies) { for (Cookie cookie : cookies) { if (Objects.equals(cookie.getName(), cookieName)) { return cookie.getValue(); } } } return null; }Copy the code

Cookie

Cookie is a client technology, but also many people to achieve Session Session selection, the server can let the client write some information into the local Cookie, to achieve the purpose of Session tracking. Note, however, that the browser disables cookies locally.

Speaking of cookies, we have to say that many advertisers and websites use our personal privacy to track, analyze our behaviors and make personalized recommendations. Many websites use third-party cookies to obtain user information and send it to the server to record user behavior track. No doubt you’ve come across a discussion about hair loss in other apps, and then you open Taobao to find a variety of shampoo recommendations for hair loss. However, some browsers have disabled or optimized third-party cookies, such as Safari, Mozilla, etc.

We can manually set some information into cookies so that the client can use the information and the server can act on it in subsequent requests.

 public void saveUserContext(HttpServletResponse response, String key, String value) {
     // 设置cookie
     Cookie cookie = new Cookie(key, value);
     cookie.setPath("/");
     // 设置有限期,负数例如-1代表Web浏览器关闭的时候删除,如果不设置就默认-1
     cookie.setMaxAge(12 * 60 * 60);
     response.addCookie(cookie);
 }
Copy the code

We can check the Cookie information stored locally through the browser, and other websites can also scan and use the cookies stored by us, so some security or confidential information should not be stored in cookies as far as possible, because the data security is relatively low. Normally, important information, such as user login information, is stored in the server Session, and other information, such as the Session ID, can be stored in cookies.

In addition, the size of a single Cookie is also limited. The limit rules vary from browser to browser. Generally, the size is several Kb. Different browsers also have a limit on the number of cookies under a domain name, generally dozens, and there are also a number of saturation elimination strategy, so pay attention to these situations, try not to exceed the limit of the browser.