Spring Boot Session with Redis
HttpSession with Redis
Last entry, I explain how to use Redis in Spring Boot.
The goal is to use HttpSession with Redis.
HttpSession is basically one machine. If you use several machines for service, this session is not used for other servers after saving data in one server.
So, we prepare cache server for session. The cache server is redis.
This is sample to use redis for HttpSession
If you don’t familiar with Redis in Spring Boot, please check my other entry : Spring Boot Redis
Dependencies
Add spring-session-data-redis
dependencies { compile("org.springframework.boot:spring-boot-starter-web") compile("org.springframework.boot:spring-boot-starter-redis") compile("org.springframework.session:spring-session-data-redis") testCompile("org.springframework.boot:spring-boot-starter-test") }
Config
To enable Redis with session, we need to add configuration setting
@Configuration @EnableRedisHttpSession public class Config { @Bean public JedisConnectionFactory connectionFactory() { return new JedisConnectionFactory(); } }
Test how it works
For test, I set session value using HttpSession in Spring Boot Controller
@RestController @RequestMapping(value="/session") public class SessionController { @RequestMapping(value="test", method=RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public String signin(HttpSession httpSession) { httpSession.setAttribute("test", "test"); return "success"; } }
To add session data, access http://localhost:8080/session/test
Check from redis
The easiest way is to use redis-cli
redis-cli keys '*'
To clear value(to check easily)
redis-cli > flushdb
The results :
1) "spring:session:expirations:1473502620000" 2) "spring:session:sessions:1fa2e596-891a-4487-8427-7437852d24c8" 3) "spring:session:sessions:expires:1fa2e596-891a-4487-8427-7437852d24c8"
If you stop redis, the value will be kept. You start redis again, the value is still alive.