Search code examples
google-cloud-platformgoogle-app-engineapp-engine-flexible

App engine flexible - how to implement distributed sessions


In the flexible environment, App Engine doesn't provide built-in support for distributed sessions like it does in the standard environment with Memcache.

So after migrating to Flex, I am unable to autoscale the application anymore as the user session cannot be routed from an instance to another like it was in Standard.

We should specify a Session Storage (eg: Redis) to have the user sessions shared between all the instances.

I looked at this google documentation https://cloud.google.com/appengine/docs/flexible/nodejs/configuring-your-app-with-app-yaml but it didn't helped me.

Any ideas ?


Solution

  • Spring Session makes it very simple !

    Include the spring-session-core & spring-session-data-redis libraries into your pom.xml file

    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-data-redis</artifactId>
    </dependency>
    

    Configure your redis configuration. 2 ways exist here

    • Option 1) Redis configuration via the properties file

    Put the below into your application.properties

    spring.data.redis.host=127.0.0.1
    spring.data.redis.port=6379
    
    • Option 2) Redis configuration from the java code
    @Configuration
    public class RedisConfiguration {
    
        private static final String redisHost = "127.0.0.1";
        private static final int redisPort = 6379;
    
        @Bean
        public RedisConnectionFactory redisConnectionFactory() {
            RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(redisHost, redisPort);
    
            return new JedisConnectionFactory(redisStandaloneConfiguration);
        }
    
    }
    

    Spring will automatically create the session in redis instead of the memory store as shown below

    enter image description here