• SpringBoot2整合Spring Session


    源码地址:https://github.com/JianLiangHe/springboot-conformity/tree/master/springboot-conformity-session01

    1.Maven依赖

    SpringBoot和Spring Session整合的配置需要引入2个依赖:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-data-redis</artifactId>
    </dependency>
    

    2.application.yml

    server:
      port: 8088
    spring:
      # redis配置
      redis:
        # ip地址
        host: 139.196.158.120 
        # 端口
        port: 26379
        # 密码
        password: root
    

      

    3.RedisSessionConfig.java 配置类

    @Configuration
    // maxInactiveIntervalInSeconds 默认是1800秒过期,这里改为60秒
    // RedisFlushMode有两个参数:ON_SAVE(表示在response commit前刷新缓存),IMMEDIATE(表示只要有更新,就刷新缓存)
    // redisNamespace : redis中的key
    @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60, 
    	redisFlushMode = RedisFlushMode.ON_SAVE, 
    	redisNamespace = "springboot-conformity-session01")
    public class RedisSessionConfig {
    
    }
    

      

    4.添加测试Controller:SessionShareController.java

    @Api
    @RestController
    @RequestMapping(value = "/sessionShare/")
    public class SessionShareController {
    
    	@Value("${server.port}")
    	private Integer port;
    	
    	@ApiOperation("set")
    	@RequestMapping(value = "set", method = RequestMethod.POST)
    	public String set(HttpSession session) {
    		session.setAttribute("user", "Jackey");
    		return String.valueOf(port);
    	}
    	
    	@ApiOperation("get")
    	@RequestMapping(value = "get", method = RequestMethod.GET)
    	public String get(HttpSession session) {
    		return "user: " + session.getAttribute("user") + ", port: " + port;
    	}
    	
    }
    

      

    5.测试结果

    1.将项目打成jar包,发布到服务器,过程略,分别使用9090、9091端口启动项目

    nohup java -jar springboot-conformity-session01-0.0.1-SNAPSHOT.jar --server.port=9090 &
    nohup java -jar springboot-conformity-session01-0.0.1-SNAPSHOT.jar --server.prot=9091 &
    

    先访问9090端口的服务set方法(此处我用swagger接口文档访问)

    再用9090和9091端口访问get方法

    9090:

    9091:

    从上面案例看,可以看出session已经实现了共享。

      

  • 相关阅读:
    CentOS8下升级Python3.6到3.9
    web service基础知识
    mysql+centos7+主从复制
    saltstack高效运维
    Docker
    python如何配置virtualenv
    Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy
    nginx+uWSGI+django+virtualenv+supervisor发布web服务器
    RabbitMQ消息队列-Centos7下安装RabbitMQ3.6.1
    flask-wtforms
  • 原文地址:https://www.cnblogs.com/hejianliang/p/14149153.html
Copyright © 2020-2023  润新知