zoukankan      html  css  js  c++  java
  • 分布式session共享

    一、前言

    为什么会出现session共享问题?

    客户端与服务器交互时会产生唯一的sessionid用于标记用户,但是在分布式架构中,如果还是采用 session 的方式,用户发起请求,通过 nginx 做请求转发时,并不知道是转发到服务器1还是服务器2,所以就会出现session共享问题。

    关于分布式 session 共享有两种解决方式,使用 spring-session 框架或者是使用 token 替代 session。

    今天主要记录使用 spring-session 框架解决 session 共享问题。

    其主要原理就是使用 redis 记录 session 实现session 共享。

    二、代码部分

    1、引入依赖
    <!--spring session 与redis应用基本环境配置,需要开启redis后才可以使用,不然启动Spring boot会报错 -->
    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
    </dependency>
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
    </dependency>
    2、application配置文件
    redis:
      hostname: 192.168.10.180
      port: 6379
      password: 123456
    3、SessionConfig
    /**
     * 这个类用配置redis服务器的连接
     * maxInactiveIntervalInSeconds为SpringSession的过期时间(单位:秒)
     */

    @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800)
    public class SessionConfig {

        /* 冒号后的值为没有配置文件时,制动装载的默认值 */
        @Value("${redis.hostname:localhost}")
        String hostName;
        @Value("${redis.port:6379}")
        int port;
        @Value("${redis.password:123456}")
        String passWord;

        @Bean
        public JedisConnectionFactory connectionFactory() {
            JedisConnectionFactory connection = new JedisConnectionFactory();
            connection.setPort(port);
            connection.setHostName(hostName);
            connection.setPassword(passWord);
            return connection;
        }
    }
    4、nginx配置
    #user  nobody;
    worker_processes  1;

    #error_log  logs/error.log;
    #error_log  logs/error.log  notice;
    #error_log  logs/error.log  info;

    #pid        logs/nginx.pid;


    events {
        worker_connections  1024;
    }


    http {
        include       mime.types;
        default_type  application/octet-stream;
        sendfile        on;


        keepalive_timeout  65;

        upstream  backServer{
            server 192.168.10.180:8080;
            server 192.168.10.180:8081;
        }
        server {
            listen       80;
            server_name  shop.sscai.club;
            location / {
               proxy_pass http://backServer;
                index  index.html index.htm;
            }      
        }
    }

    我创建了一个java相关的公众号,用来记录自己的学习之路,感兴趣的小伙伴可以关注一下微信公众号哈:niceyoo

  • 相关阅读:
    CentOS7使用firewalld打开关闭防火墙与端口
    SELinux: Could not downgrade policy file
    CentOS 安装 semanage 命令
    漏洞: RHSA2017:3075: wget security update
    CentOS7增加或修改SSH端口号
    gnl's not lao 道德经 英文版
    当代 IT 大牛排行榜
    当代 IT 大牛排行榜
    2008 年个人回忆与总结
    Patch2 for NetBeans IDE 6.5 Now Available
  • 原文地址:https://www.cnblogs.com/niceyoo/p/11258392.html
Copyright © 2011-2022 走看看