Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to store session in Redis using Java Spring Boot Session Data Redis

I think I have problems saving session information in Redis. I've tried to follow the instruction about spring-session-data-redis, but I can't find any session information within redis when I start a request. The following is my code and config.

application.properties file:

spring.session.store-type=redis
spring.session.redis.flush-mode= on-save
spring.session.redis.namespace= spring:session
spring.redis.host= 10.10.10.10
spring.redis.port=10000

pom.xml:

<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
    <type>jar</type>
</dependency>

Application Configuration class:

@Configuration
@EnableRedisHttpSession
@PropertySource("application.properties")
public class AppConfig {

    @Value("${spring.redis.host}")
    private String redisHostName;

    @Value("${spring.redis.port}")
    private int redisPort;

    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(
                redisHostName, redisPort);
        return new JedisConnectionFactory(redisStandaloneConfiguration);
    }
}

And my sample Get request controller:

// test only
    @CrossOrigin
    @GetMapping(value = "/test/test")
    public String justTest(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("sessionId", "ssssss");

        String value = (String) session.getAttribute("sessionId").toString();
        return value;
    }

Am I missing something? The spring-session-data-redis is supposed to store session to Redis automatically, but it seems not acting like that. Do I need spring-session dependency and spring-data-redis dependency? The redis connection is ok, I set it to listen to all interfaces.

It seems I can retrieve the session id when I start a request, but why the session is not inserted into Redis?

like image 445
billcyz Avatar asked Jul 08 '18 06:07

billcyz


1 Answers

spring.session.redis.flush-mode= IMMEDIATE

/**
     * Flush mode for the Redis sessions. The default is {@code ON_SAVE} which only
     * updates the backing Redis when {@link SessionRepository#save(Session)} is invoked.
     * In a web environment this happens just before the HTTP response is committed.
     * <p>
     * Setting the value to {@code IMMEDIATE} will ensure that the any updates to the
     * Session are immediately written to the Redis instance.
     * @return the {@link RedisFlushMode} to use
     * @since 1.1

Link to docs

like image 82
user9482905 Avatar answered Nov 12 '22 08:11

user9482905