http性质
- http是简单的
- http是可扩展的
- http是无状态的、有会话的:在同一个链接中,每个请求之间是没有关系的。http本身是无状态的,使用cookies可以创建有状态的会话。
cookie是服务器发送到浏览器,并保存在浏览器端端一小块数据;浏览器下次访问该服务器时会自动携带块该数据,将其发送给服务器
demo
//cookie
@RequestMapping(path = "/cookie/set", method = RequestMethod.GET)
@ResponseBody
public String setCookie(HttpServletResponse response){
// create cookie
Cookie cookie = new Cookie("code", CommunityUtil.generateUUID());
// Sets the range over which the cookie is valid
cookie.setPath("/myCommunity/alpha");
// if you set a lifetime of cookie, it will store in your disk
cookie.setMaxAge(60 * 10); // 10 min
// send cookie
response.addCookie(cookie);
return "set cookie";
}
@RequestMapping(path = "/cookie/get", method = RequestMethod.GET)
@ResponseBody
public String getCookie(@CookieValue("code") String code){ // 我们上边set了code的值
System.out.println(code);
return "get cookie";
}
session
由于cookie是由浏览器保存在本地的,所以稳定性很低。还可以使用session来保存记录,在通信时穿一个session(cookieid),由服务器保存,以后通信时服务器自己去查找相应的cookieid
demo
// demo of session
@RequestMapping(path = "/session/set", method = RequestMethod.GET)
@ResponseBody
public String setSession(HttpSession session){
session.setAttribute("id", 1);
session.setAttribute("name", "Test");
return "set session";
}
@RequestMapping(path = "/session/get", method = RequestMethod.GET)
@ResponseBody
public String getSession(HttpSession session){
System.out.println(session.getAttribute("id"));
System.out.println(session.getAttribute("name"));
return "get session";
}
实际应用
分布式部署时使用session比较少,分布式部署通常有多台服务器,前面由nginx来负责负载均衡。
有可能浏览器第一次访问时,服务器1比较空闲,此时在服务器1创建了一个session;而当浏览器第二次访问时,不一定访问的服务器1,又要重新创建session。
解决办法:
- 粘性session:同一个ip只给一个服务器负责。这种方法性能不好,难以保证服务器是负载均衡的
- 同步session:一台服务器创建session,同时同步给其他服务器。影响性能,服务器耦合度高
- 共享session:单独用一个服务器存放session,其他服务器访问该服务器获取session。但是安全度低。
主流办法是尽量用cookie,不能用cookie的就用数据库集群(redis)来保存session。