SpringBoot+Session+redis实现分布式登录
在Spring Boot中,使用Spring Session和Redis实现分布式登录可以通过以下步骤实现:
- 在
pom.xml
中添加依赖:
<!-- Spring Boot Starter Data Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Spring Session for Redis -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
- 在
application.properties
或application.yml
中配置Redis服务器:
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# 连接池最大连接数(使用默认值即可)
# spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用默认值即可)
# spring.redis.pool.max-wait=-1
# 连接池中最大空闲连接
# spring.redis.pool.max-idle=8
# 连接池中最小空闲连接
# spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
# spring.redis.timeout=0
- 配置Spring Session使用Redis:
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600)
public class SessionConfig {
}
- 创建登录接口,并在登录成功后将用户信息存入session:
@RestController
public class LoginController {
@PostMapping("/login")
public String login(@RequestParam String username, HttpSession session) {
// 登录逻辑...
session.setAttribute("username", username);
return "Login successful";
}
}
- 配置Spring Security以使用Redis存储会话信息:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// ... 其他配置 ...
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.maximumSessions(1)
.expiredUrl("/login?expired");
}
@Bean
public CookieSerializer cookieSerializer() {
DefaultCookieSerializer serializer = new DefaultCookieSerializer();
serializer.setCooki
评论已关闭