Java工作笔记-Nginx配置IPHash(单点登录)
生活随笔
收集整理的這篇文章主要介紹了
Java工作笔记-Nginx配置IPHash(单点登录)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
拓撲圖是這樣的
iphash實現原理:
記錄ip地址,生成iphash值,用這個值去綁定一臺服務器,以后這個client的請求都會訪問到綁定到的服務器中,這里生成iphash一般是通過Nginx進行生成,然后綁定。
缺點,失去了負載均衡的意義,單點故障,當某個服務器宕機后,服務器上的iphash都會掛了。中小企業用得多,用戶信息不敏感。
?
Nginx配置如下:
worker_processes 1;events {worker_connections 1024; }http {upstream ipHashDemo{ip_hash;server 127.0.0.1:8081;server 127.0.0.1:8082;}server{listen 8888;server_name 127.0.0.1;location / {proxy_pass http://ipHashDemo;}} }這里有一個要注意的,上個的server_name里面的prox_pass。
ipHashDemo要和upstream ipHashDemo相對應。
程序運行截圖如下,登錄用戶和獲取,都是在IPHashServer1中,這也是ipHashDemo:
關鍵源碼如下:
IPHashServer1中
Server1Controller.java
package cn.it1995.ipHash.controller;import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpSession; import java.util.HashMap; import java.util.Map;@RestController public class Server1Controller {@GetMapping("/login")public Object userLogin(@RequestParam("username") String username,@RequestParam("password") String password,HttpSession session){session.setAttribute("username", username);session.setAttribute("password", password);Map<String, Object> ret = new HashMap<>();ret.put("result", "登錄成功");return ret;}@GetMapping("getUser")public Object getUser(HttpSession session){Object username = session.getAttribute("username");Object password = session.getAttribute("password");Map<String, Object> ret = new HashMap<>();ret.put("用戶名", username);ret.put("密碼", password);ret.put("當前服務器名稱", "IPHashServer1");return ret;} }IPHashServer2中
Server2Controller.java
package cn.it1995.ipHash.controller;import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpSession; import java.util.HashMap; import java.util.Map;@RestController public class Server2Controller {@GetMapping("/login")public Object userLogin(@RequestParam("username") String username,@RequestParam("password") String password,HttpSession session){session.setAttribute("username", username);session.setAttribute("password", password);Map<String, Object> ret = new HashMap<>();ret.put("result", "登錄成功");return ret;}@GetMapping("getUser")public Object getUser(HttpSession session){Object username = session.getAttribute("username");Object password = session.getAttribute("password");Map<String, Object> ret = new HashMap<>();ret.put("用戶名", username);ret.put("密碼", password);ret.put("當前服務器名稱", "IPHashServer2");return ret;} }?
?
總結
以上是生活随笔為你收集整理的Java工作笔记-Nginx配置IPHash(单点登录)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java文档阅读笔记-Spring Bo
- 下一篇: Java笔记-使用jjwt生成jwt