一、准备工作
| 项 | 版本 | 更新或下载URL | ||
| Windows 10 | 64位 | 略 | ||
| IntelliJ IDEA | 2017.1.5 | IntelliJ IDEA: The Capable & Ergonomic Java IDE by JetBrains | ||
| JDK8 | 64位 | [Java Downloads | Oracle](www.oracle.com/technetwork… "Java Downloads | Oracle") |
| redis | 3.2.100 | github.com/MSOpenTech/… |
Spring-data-redis Jar包
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.0.1.RELEASE</version>
</dependency>
jedis jar包
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
二、搭建步骤
1. 安装redis
1.1 下载Windows redis
下载地址见准备工作步骤。
1.2 解压redis至自定义目录
1.3 设置redis需要访问密码
1) 找到redis所在目录的redis.windows.conf文件的requirepass字段,去掉注释,修改你需要的密码
2) 设置永久登录需要密码连接
1.4 启动redis
2. 建立Spring boot项目
2.1 新建Spring boot项目
2.2 Maven依赖、JDK、Package设置
2.3 项目依赖项选择(pom.xml文件内均可查看)
2.4 新建项目成功,依据pom.xml文件自动更新jar
本地仓库默认路径:${user.home}/.m2/repository,也可以自行设定
2.5 运行Spring boot 应用是否能启动
未添加相关的redis支持项时无法正常启动。
添加相关配置,步骤如下:
-
application.properties
-
pom.xml
-
CodeCaptionApplication.java
2.6 重新启动Spring boot应用,并访问session测试路径
访问路径:
http://localhost:8080/sessionRedis/test
访问结果:
此步骤需要添加的controller源码见附录。
至此已能正常访问集成session+redis的Spring boot应用。源码下载地址见准备工作。
三、 FAQ
1. Spring-boot-redis与jedis版本不一致
-
应用无法正常启动;
-
Jedis对应jar包版本大于2.4.2,详细情况请在Maven官网进行查询。
2. Redis服务端设置临时密码方式
- 打开cmd命令行
- 进入redis所在目录
- 使用startup.bat脚本启动redis服务
- 输入命令redis-cli –h 127.0.0.1 –p 6379 登录至客服端
- 设置临时密码:config set requirepass <你的密码>
- 查看密码设置情况:config get requirepass
- 结果如下:(密码设置后需要重新登录)
四、 附录
1. Maven本地仓库设置文件settings.xml下载路径
已添加阿里云仓库更新地址(位于测试工程源码下载地址的xml文件夹下)。
2. Maven仓库
查询地址: mvnrepository.com/
3. Redis startup.bat脚本
内容
redis-server.exe redis.windows.conf
4. com.example.controller.TestController.java源码
package com.example.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
@SuppressWarnings("unchecked")
@RestController
public class TestController
{
private Logger logger = LoggerFactory.getLogger(this.getClass());
@RequestMapping("/sessionRedis/test")
public ResponseEntity<?> httpSessionRedisTest(HttpSession httpSession)
{
if (httpSession.isNew()) {
logger.info("Successfully creates a session ,the id of session :" + httpSession.getId());
httpSession.setAttribute("key", "hello");
} else {
logger.info("session already exists in the server, the id of session :" + httpSession.getId());
logger.info(httpSession.getAttribute("key").toString());
}
ResponseEntity<?> entity = new ResponseEntity<Object>("Hello world, session id:" + httpSession.getId(), HttpStatus.OK);
return entity;
}
}
效果图:
五、示例代码
Spring boot session + redis
GitHub - Cavan2477/SpringBoot-Session-Redis: Spring boot + redis 实现session 共享管理