将nginx,java,mysql分别安在不同的服务器上
1.安装openresty, 按照官网操作
https://openresty.org/en/linux-packages.html
https://openresty.org/cn/getting-started.html
#启动openresty
systemctl start openresty.service
2.动静分离服务器
location节点path为resources的访问静态资源路径
location节点其他路径访问动态资源
2.1 将静态文件html等放入/usr/local/openresty/nginx/html/resources目录下
2.2 修改nginx.conf文件,使http://miaoshaserver/resources/register.html能访问后台静态文件
其他请求访问backend_server中的动态资源。
upstream backend_server{
server 127.0.0.1:8090 weight=1;
server 192.168.31.65:8090 weight=1;
}
server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location /resources/ { alias /usr/local/openresty/nginx/html/resources/; index index.html index.htm; }
location / {
proxy_pass http://backend_server/;
proxy_set_header Host $http_host:$proxy_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarder_for;
}
重启nginx [root@iZbp1dtm752cu7uoi7cj5fZ nginx]# sbin/nginx -s reload
查看启动是否正常 [root@iZbp1dtm752cu7uoi7cj5fZ logs]# tail -f error.log
2.3 开启access.log查看nginx转发情况, 在application.properties中配置
#打开accesslog
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.directory=/root/temp/tomcat
server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b %D
3.分布式会话redis实现
redis下载安装:https://www.redis.net.cn/download/
redis启动: ./redis-server --protected-mode no &
application.properties文件增加redis配置
#配置springboot对redis的依赖 spring.redis.host=47.99.51.246 spring.redis.port=6379 spring.redis.database=10 #设置jedis连接池 spring.redis.jedis.pool.max-active=50 spring.redis.jedis.pool.max-idle=20
新建RedisConfig.java,注入redis Bean
@Component @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600) public class RedisConfig { }
UserController.java登录时设置Session时,会自动在redis中存储sessionId,这样分布式会话就可以共享了
this.httpServletRequest.getSession().setAttribute("IS_LOGIN",true);
this.httpServletRequest.getSession().setAttribute("LOGIN_USER",userModel);
4.基于token传输类似sessionId,实现会话共享
之前是基于cookie传输sessionId
现在是将token保存在redis中
// 若登录成功将登录凭证和登录信息一起放到redis中 String uuidTocken = UUID.randomUUID().toString(); //将登陆凭证加入到用户登陆成功的session内 /* * this.httpServletRequest.getSession().setAttribute("IS_LOGIN",true); * this.httpServletRequest.getSession().setAttribute("LOGIN_USER",userModel); */ redisTemplate.opsForValue().set(uuidTocken, userModel); redisTemplate.expire(uuidTocken, 1, TimeUnit.HOURS); // 下发tocken给前台 return CommonReturnType.create(uuidTocken);
login.html,将下发的token保存到localStorage中
success:function(data){
if(data.status == "success"){
alert("登陆成功");
var token = data.data;
window.localStorage["token"] = token;
window.location.href="listitem.html";
}
getitem.html 下单时需传递token
$("#createorder").on("click",function(){
var token = window.localStorage["token"];
if(token==null){
alert("用户还未登录,请先登录");
window.location.href="login.html";
}
$.ajax({
type:"POST",
contentType:"application/x-www-form-urlencoded",
url:globalHost+"/order/createorder?token="+token,
data:{