1、技術:springboot、nginx;
練習springboot前后端分離,且用nginx代理部署,實現前后端分離。
控制層添加json數據,並返回json.
@RestController @RequestMapping("/student") public class StudentController { @RequestMapping("/studentById") public JSONObject selectStudentById(String id, HttpServletRequest request, HttpServletResponse response) { response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Cache-Control", "no-cache"); /*
{ "name":"smith". "age":30, "sex":"男" }
*/ JSONObject jsonObject = new JSONObject(); jsonObject.put("name","smith"); jsonObject.put("age","30"); jsonObject.put("sex","男"); return jsonObject; } }
2、安裝nginx。(過程省略)
2.1 在D:\xxxx\nginx-1.18.0\html 這個文件下添加一個頁面 users.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <title>layui在線調試</title> <style> body{margin: 10px;} .demo-carousel{height: 200px; line-height: 200px; text-align: center;} </style> <script src="/js/jquery.js"></script> </head> <body> <button id="btn" onclick="threeFn()">點我</button> <h3 id="aaa"></h3> <script> function threeFn(){ alert("請求了!!!"); //向服務端發送刪除指令 $.ajax({ type: "get", url: "/oa/student/studentById", dataType:'json', success: function (data) { alert(data.name); //取json中的name,打印在頁面中
document.getElementById("aaa").innerHTML=data.name; } }); } </script> </body> </html>
2.2 nginx的配置文件nginx.conf配置
#配置文件讀取根路徑下的靜態文件 root后面的html,意思是nginx下的html文件夾
location / {
root html;
index index.html index.htm;
}
# 配置代理地址 注意:oa是代表下面的 IP+port,請求url如頁面中所示 port則是springboot中設置的或者默認的
location /oa/ {
proxy_pass http://127.0.0.1:8384/; #注意:使用代理地址時末尾記得加上斜杠"/"。
}
2.3 負載均衡配置
http {
#服務器組名稱
#不同IP相同端口也可以,相同IP不同端口也可以。
upstream mysvr {
#weigth參數表示權值,權值越高被分配到的幾率越大
ip_hash;
#server 192.168.84.130:8384 weight=1;
server 127.0.0.1:8385 weight=5;
server 127.0.0.1:8384 weight=1;
}
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
location /oa/ { #oa這個名字是需要在頁面url配置的。
#proxy_pass http://127.0.0.1:8384/; #注意:使用代理地址時末尾記得加上斜杠"/"。
# http://服務器組名稱/; 切記 / 不能丟。
proxy_pass http://mysvr/;
}
}
}
3、啟動nginx,瀏覽器輸入http://127.0.0.1/users.html,如圖所示

點擊按鈕

nginx代理成功。。。
一步步繼續深入學習。
