Spring Session+Redis实现分布式Session共享

  • 1.新建一个SpringBoot项目

  • 2.引入SpringSession依赖

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--spring session 与redis应用基本环境配置,需要开启redis后才可以使用,不然启动Spring boot会报错 -->
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
  • 3.编写配置文件此处为application.properties
server.port=8080
##redis配置
spring.redis.database=1
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=1000
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.min-idle=0
##session超时配置默认是秒
spring.session.timeout=30
  • 3.编写接口进行测试
package com.example.demo.sys.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.sys.service.TestService;

@RestController
@RequestMapping("/")
public class TestSessionController {

	@Autowired
	private TestService testService;

	@Value("${server.port}")
	private Integer projectPort;

	@RequestMapping("/createSession")
	public String createSession(HttpSession httpSession, String name) {
		httpSession.setAttribute("name", name);
		return "当前项目端口:[" + projectPort + "] 当前sessionId:[" + httpSession.getId() + "] 在session中存入成功!";
	}

	@RequestMapping("/getSession")
	public String getSession(HttpSession session) {
		return "当前项目端口:" + projectPort + " 当前sessionId :" + session.getId() + "  获取的姓名:"
				+ session.getAttribute("name");
	}

	@RequestMapping("/test")
	public String test() {
		testService.test();
		return "success";
	}

}

启动多例进行测试

你可能感兴趣的:(Springboot框架,SpringCloud服务,spring,boot,redis)