Fork me on GitHub

在SpringBoot中存放session到Redis

前言

今天你们将再一次领略到SpringBoot的开发到底有多快,以及SpringBoot的思想(默认配置)

我们将使用redis存放用户的session,用户session存放策略有很多,有存放到内存的,有存放数据库的,也有存放redis。这里我们使用redis存放,目的是,当服务器重启,用户的session信息也没有丢失。

已经加入我的github模版中:https://github.com/LinkinStars/springBootTemplate

 

实现

添加gradle依赖

compile group: 'org.springframework.session', name: 'spring-session-data-redis', version: '1.3.1.RELEASE'

新增类

import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

/**
 * session存放redis*/
@Configuration
@EnableRedisHttpSession
public class RedisSessionConfig {
}

在controller中添加验证代码

//测试session存放redis测试
        HttpSession session = request.getSession();
        System.out.println("session数据:" + session.getAttribute("xxx"));
        session.setAttribute("xxx","123");
        System.out.println("session数据:" + session.getAttribute("xxx"));

然后本地启动redis,启动springboot

就可以了

对,你没有听错,就是可以了。这就是springboot的魅力,项目中添加一个功能非常的简单,而且耦合度非常低,如果你有一天不用了,直接把这个类删除就可以了。然后一点,之所以完成了,是因为springboot默认了很多的配置,如默认redis地址为本地,默认端口号为6379等

如果你需要配置当然也是没有问题的,在application.yml进行配置就可以,更多的配置在这里就不列举了。

spring:

     #redis相关配置
    redis:
      host: localhost
      port: 6379

 

问题和参考

针对redis的使用在之后会进行更新,下面记录出现的一个问题

(error) MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk.

解决方案是:

127.0.0.1:6379> config set stop-writes-on-bgsave-error no
OK

 

参考来自:https://www.cnblogs.com/anny-1980/p/4582674.html

https://www.cnblogs.com/sweetchildomine/p/6984596.html

posted @ 2018-02-07 09:57  LinkinStar  阅读(543)  评论(0编辑  收藏  举报