springboot 使用redis 實現session共享


說明:在工程項目需求很大的情況下,部署項目的時候可能會使用分布式部署或者集群,這樣的跨服務器使用的時候,session就會出現丟失,這個時候可以使用redis共享session

一:導包

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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-data-redis</artifactId>
        </dependency>
    </dependencies>

 

二:配置redis 信息

spring.redis.host=127.0.0.1
spring.redis.port=6379

 

三:配置啟動類

@SpringBootApplication
@EnableRedisHttpSession(maxInactiveIntervalInSeconds= 1800) //spring在多長時間后強制使redis中的session失效,默認是1800.(單位/秒)
public class DemoApplication {

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

 

四:寫controller進行測試

//測試redis
@GetMapping("/testRedis")
public AjaxResult test1(HttpSession session) throws Exception{
//RedisCache.setStr(String.valueOf(utils.getNowTimeSecond()),(String) SecurityUtils.getSubject().getSession().getId());
//RedisCache.setStr(String.valueOf(utils.getNowTimeSecond()),String.valueOf(session.getId()));

session.setAttribute("admin","haha");
String haha = (String) session.getAttribute("admin");
return new AjaxResult(session.getId()+"----"+haha);
}

@GetMapping("/getRedis")
public AjaxResult test2(HttpSession session) throws Exception{
//RedisCache.setStr(String.valueOf(utils.getNowTimeSecond()),(String) SecurityUtils.getSubject().getSession().getId());
//RedisCache.setStr(String.valueOf(utils.getNowTimeSecond()),String.valueOf(session.getId()));
String haha = (String) session.getAttribute("admin");
return new AjaxResult(haha);
}

 

這樣的話,session就保存到到了redis中,可查看key值為spring:session:sessions進行查看.

 

退出后,redis中的session失效.

如不自動退出,到了"過程3"中配置的@EnableRedisHttpSession(maxInactiveIntervalInSeconds= 3600) 時間后,redis中的session也會自動失效.

 

 

在這個過程中出現的坑:jar包版本沖突,最主要的是,我使用的版本和springboot的版本一致竟然都不行,然后我就使用的最新的版本:

<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM