0

My web application uses Neo4j as a data storage, and it uses Spring Data Neo4j 4 framework.

As suggested in the tutorial, my neo4j session is bound to my HTTP session:

@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public Session getSession() throws Exception {
    return super.getSession();
}

I have an endpoint which runs a time-consuming query, and sends the result offline. I'd like to move this method to an @Async thread, but obviously I can not access my neo4j session from that thread.

What is the best practise to access neo4j repositories outside of the HTTP session without changing the scope of the "main" session bean?

endrec
  • 447
  • 6
  • 17

2 Answers2

1

I'm not sure about best practice but can't you just create another session from the sessionFactory#openSession() method? And pass that new session to another instance of neo4jOperations (or @Override the existing bean if are not using it) thus avoiding using the proxyScoped Neo4jConfiguration#getSession() method.

like so:

// note below assumes you are extending Neo4jConfiguration

// ... 

// passing in your own non proxyScoped session. 
// @Override existing neo4jTemplate @Bean passing in your own session

@Bean
@Override
public Neo4jOperations neo4jTemplate() throws Exception {
    return new Neo4jTemplate(getSessionFactory().openSession());
}

// or create another neo4jTemplate instance that avoids getSession() proxyScope method usage in its constructor. 

@Bean("nonProxyScopedNeo4jOperations")
public Neo4jOperations nonProxyScopedNeo4jTemplate() throws Exception {
    return new Neo4jTemplate(getSessionFactory().openSession());
}

// ...

and using the custom neo4jOperations bean to perform your @Async logic

see Neo4jConfiguration:

Selwyn
  • 3,118
  • 1
  • 26
  • 33
  • I was thinking of doing something similar, but it just did not feel right... I'm wondering if there is a better/simpler/eleganter (:))/springier way. – endrec Feb 16 '16 at 22:18
  • @endrec once the `getSession()` is proxy scoped for HttpSession it will be in that scope for the life of application and create a new ne4j session for each HttpSession. I don't think there's a way around it using getSession. – Selwyn Feb 16 '16 at 23:42
1

I have ended up moving my neo4jSession to a thread scope. As our application is stateless, our session is only one request. And as every request is handled in a separate thread, thread scope was the easiest way.

I'd like to thank to the developer of https://github.com/devbury/spring-boot-starter-threadscope , made my life easier. :)

endrec
  • 447
  • 6
  • 17
  • Hey endrec, it'll be very useful if you add a code snippet. – Adam G Feb 10 '17 at 09:13
  • @AdamGhani It was a while ago, but as I remeber I did not do any code change, just added the mentioned project as a dependency. – endrec Feb 16 '17 at 20:04