Search code examples
javajettydropwizardsession-management

Dropwizard Session Clustering


I need a way to share the session across different dropwizard web services. In Jetty there is a way to do it by using JDBCSessionIdManager and JDBCSessionManager (http://wiki.eclipse.org/Jetty/Tutorial/Session_Clustering).

The problem is that dropwizard (0.7.1) does not expose a reference of the org.eclipse.jetty.server.Server that is needed so there is no obvious way to do change the SessionManager and the SessionIdManager. I've seen that the Server is created in io.dropwizard.cli.ServerCommand#run through a io.dropwizard.server.ServerFactory but the reference in io.dropwizard.cli.ServerCommand#run is local so I can't even use reflection to get the reference that I want.

What should I do in dropwizard to change SessionManager and the SessionIdManager?

Thanks,
Alex


Solution

  • I was able to get it working by hooking into the life cycle.

    private void addSessionHandler(final Environment env, final DataSource dataSource) {
        env.lifecycle().addLifeCycleListener(new AbstractLifeCycleListener() {
            @Override
            public void lifeCycleStarting(LifeCycle event) {
                if (!(event instanceof Server)) {
                    return;
                }
    
                Server server = (Server) event;
                JDBCSessionIdManager ids = jdbcSessionIdManager(server);
                server.setSessionIdManager(ids);
                env.servlets().setSessionHandler(new SessionHandler(jdbcSessionManager(ids)));
            }
    
            private JDBCSessionManager jdbcSessionManager(JDBCSessionIdManager idManager) {
                JDBCSessionManager m = new JDBCSessionManager();
                m.setSessionIdManager(idManager);
                return m;
            }
    
            private JDBCSessionIdManager jdbcSessionIdManager(Server server) {
                JDBCSessionIdManager m = new JDBCSessionIdManager(server);
                m.setWorkerName("");
                m.setDatasource(dataSource);
                return m;
            }
        });
    }