springSession

2022-08-16 19:15:17 浏览数 (1)

慎易以避难,敬细以远大。一一韩非子

依赖管理器

代码语言:javascript复制
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.session</groupId>
      <artifactId>spring-session-bom</artifactId>
      <version>Corn-SR2</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

依赖

代码语言:javascript复制
<dependencies>
  <dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
  </dependency>
</dependencies>

然后是配置

代码语言:javascript复制
spring: 
  session:
    store-type: redis
    timeout: 30m

之后使用session时就自动使用redis替换啦

代码语言:javascript复制
package com.ruben.controller;

import com.ruben.enumeration.GenderEnum;
import com.ruben.pojo.po.UserPO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/config")
@RefreshScope
public class ConfigController {

    @Resource
    private HttpServletRequest httpServletRequest;

    @RequestMapping("session")
    public String session() {
        httpServletRequest.getSession().setAttribute("sessionTest", UserPO.builder().id(1).build());
        return "ok";
    }


}

然后如果我们需要配置子域session共享或者更改session名字

可以写一个配置类

代码语言:javascript复制
package com.ruben.config;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.session.web.http.DefaultCookieSerializer;

/**
 * @ClassName: SessionConfig
 * @Description: 我还没有写描述
 * @Date: 2021/3/10 0010 21:33
 * *
 * @author: <achao1441470436@gmail.com>
 * @version: 1.0
 * @since: JDK 1.8
 */
@Configuration
public class SessionConfig {

    @Bean
    public CookieSerializer cookieSerializer() {
        DefaultCookieSerializer serializer = new DefaultCookieSerializer();
        serializer.setDomainName("utools.club");
        serializer.setCookieName("RUBEN_SESSION");
        return serializer;
    }

    @Bean
    public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
        return new GenericFastJsonRedisSerializer();
    }
}

然后我们访问即可看到成功更改

0 人点赞