springboot集成Spring Session配置

2024-06-21 07:32

配置步骤

步骤1

创建项目

image.png

步骤2

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>cn.guangjun.spring.boot2</groupId>
        <artifactId>springboot2-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <artifactId>springboot2-session</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot2-session</name>
    <description>springboot2-session</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.17</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.4</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

步骤3

application.yaml

server:
  port: 9000
spring:
  datasource:
    druid:
      url: jdbc:mysql://172.17.4.136:3603/springboot2?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=CTT
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: P@ssw0rd
      initial-size: 2
      max-active: 2
      min-idle: 1
      max-wait: 1000
      #preparestatement
      pool-prepared-statements: true 
      max-pool-prepared-statement-per-connection-size: 20
      max-open-prepared-statements: 20 
      validation-query: select 1 
      validation-query-timeout:  2000
      
      test-on-borrow: false
      test-on-return: false
      test-while-idle: true 
      time-between-eviction-runs-millis: 2000 
      min-evictable-idle-time-millis: 600000
      max-evictable-idle-time-millis: 900000
      filters:  stat,wall,log4j #??????????
      filter:
        stat:
          enabled: true
          db-type: mysql
          log-slow-sql: false
          slow-sql-millis: 2000
        wall:
          enabled: true
          db-type: mysql
          config:
            delete-allow: false
            drop-table-allow: false
      aop-patterns: com.alibaba.druid.spring.boot.demo.service.*
      web-stat-filter:
#        enabled: true #????StatFilter???false
#        url-pattern: 
#        exclusions: 
#        session-stat-enable: 
#        session-stat-max-count: 
#        principal-session-name: 
#        principal-cookie-name: 
#        profile-enable: 
        enabled: true
        url-pattern: "/*"
        exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
      # StatViewServlet????????Druid Wiki???_StatViewServlet??
      stat-view-servlet:
        url-pattern: "/druid/*"
        # IP???(????????????????)
        allow: 127.0.0.1
        # IP??? (??????deny???allow)
        deny: 192.0.0.1
        #  ??HTML?????Reset All???
        reset-enable: false
        # ???
        login-username: admin
          # ????
        login-password: 123456
        # ??????????????????
        enabled: true
  redis:
    database: 10
      # Redis IP
    host: 172.17.4.136
    password: Hu@123#!
    client-type: jedis
    jedis:
      pool:
        max-active: 50
        max-wait: 5
        max-idle: 20
        min-idle: 5
    timeout: 5000
        

步骤4

@Configuration
//maxInactiveIntervalInSeconds:设置session有效时间 默认1800,单位秒。
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60*30)
public class HttpSessionConfig {
    @Bean
    public ServletListenerRegistrationBean servletListenerRegistrationBean(){
        ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean();
        servletListenerRegistrationBean.setListener(new OnLineCountListener());
        return servletListenerRegistrationBean;
    }
}

@WebListener
public class OnLineCountListener implements HttpSessionListener {
    private final static Logger LOG = LoggerFactory.getLogger(OnLineCountListener.class);

    private AtomicInteger onLineCount = new AtomicInteger(0);

    public void sessionCreated(HttpSessionEvent event) {
        LOG.info("创建Session");
        event.getSession().getServletContext().setAttribute("onLineCount", onLineCount.incrementAndGet());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        LOG.info("销毁Session");
        event.getSession().getServletContext().setAttribute("onLineCount", onLineCount.decrementAndGet());
    }
}
@WebListener
public class SessionListener implements HttpSessionListener, HttpSessionAttributeListener {
    public static final Logger logger= LoggerFactory.getLogger(SessionListener.class);

    @Override
    public void  attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        logger.info("--attributeAdded--");
        HttpSession session=httpSessionBindingEvent.getSession();
        logger.info("key----:"+httpSessionBindingEvent.getName());
        logger.info("value---:"+httpSessionBindingEvent.getValue());

    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
        logger.info("--attributeRemoved--");
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
        logger.info("--attributeReplaced--");
    }

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        System.out.println("---sessionCreated----");
        logger.info("---sessionCreated----");
        HttpSession session = event.getSession();
        ServletContext application = session.getServletContext();
        // 在application范围由一个HashSet集保存所有的session
        HashSet sessions = (HashSet) application.getAttribute("sessions");
        if (sessions == null) {
            sessions = new HashSet();
            application.setAttribute("sessions", sessions);
        }
        // 新创建的session均添加到HashSet集中
        sessions.add(session);
        // 可以在别处从application范围中取出sessions集合
        // 然后使用sessions.size()获取当前活动的session数,即为“在线人数”
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) throws ClassCastException {
        logger.info("---sessionDestroyed----");
        HttpSession session = event.getSession();
        logger.info("deletedSessionId: "+session.getId());
        System.out.println(session.getCreationTime());
        System.out.println(session.getLastAccessedTime());
        ServletContext application = session.getServletContext();
        HashSet sessions = (HashSet) application.getAttribute("sessions");
        // 销毁的session均从HashSet集中移除
        sessions.remove(session);
    }

}

步骤5

@RestController
public class SessionController {

    @RequestMapping("/session1")
    public Object session1(@RequestParam("username") String username, HttpServletRequest request, HttpSession session) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().contains("JSESSION")) {
                    System.out.println(cookie.getName() + "=" + cookie.getValue());
                }
            }
        }
        Object value = session.getAttribute("username");
        if (value == null) {
           
            session.setAttribute("username", "{username: '" + username+ "', age: 28}");

            value = session.getAttribute("username");
        } else {
            System.out.println("用户存在");
        }
        return "username=" + value;
    }

    @RequestMapping("/session2")
    public Object session2(@RequestParam("username") String username, HttpServletRequest request, HttpSession session) {
       session.setAttribute("username",username);
       return username;
    }
}

步骤6


测试


image.png


image.png

相关新闻
热点
视频
投票
查看结果
Tags

站点地图 在线访客: 今日访问量: 昨日访问量: 总访问量:

© 2025 个人网站 版权所有

备案号:苏ICP备2024108837号

苏公网安备32011302322151号