Springboot 开发 -- Redis实现分布式Session
在Spring Boot中,要实现基于Redis的分布式Session,你需要做以下几步:
- 添加依赖:确保你的
pom.xml
包含Spring Session和Redis的依赖。
<dependencies>
<!-- Spring Session for Redis -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
- 配置application.properties或application.yml:
# Redis 配置
spring.redis.host=localhost
spring.redis.port=6379
# 开启Spring Session支持
spring.session.store-type=redis
- 确保你的Spring Boot应用启动类继承了
SpringBootServletInitializer
并且被@EnableRedisHttpSession
注解。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentRegistration;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
@SpringBootApplication
@EnableRedisHttpSession
public class Application extends SpringBootServletInitializer implements ServletContextInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public ServletComponentRegistration servletComponentRegistration() {
// 如果你使用了WebSocket等其他Servlet组件,在这里进行注册
return null;
}
}
- 在你的Controller中,你可以像使用普通Session一样使用分布式Session。
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
@RestController
public class SessionController {
@RequestMapping("/setSession")
public String setSession(HttpSession session) {
session.setAttribute("key", "value");
return "Session set";
}
@RequestMapping("/getSession")
public String getSession(HttpSession session) {
return (String) session.getAttribute("key");
}
}
以上步骤配置完成后,你的Spring Bo
评论已关闭