慎易以避难,敬细以远大。一一韩非子
依赖管理器
1 2 3 4 5 6 7 8 9 10 11
| <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>
|
依赖
1 2 3 4 5 6
| <dependencies> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency> </dependencies>
|
然后是配置
1 2 3 4
| spring: session: store-type: redis timeout: 30m
|
之后使用session
时就自动使用redis
替换啦
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| 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
名字
可以写一个配置类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| 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;
@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(); } }
|
然后我们访问即可看到成功更改