jpa repository websocket #MessageMapping - spring-websocket

I found out, that spring does not create a transaction for websocket requests that are going to a action annotated with #MessageMapping. Even if i annotate the action as #Transactional nothing happens.
I also tried the way with an action that is #RequestMapping annotated. This works as usual.
Has someone an idea how i can make this work? How to make an websocket request transactional?

You shoould show your code, because it really works, unless you have some async internal logic, which doesn fit for single-threaded transactional boundries.

I fixed this issue by my self:
I just had to rename my entity manager factory to entityManagerFactory... Thats it.

Related

Passing data from a POST request and broadcasting to a websocket in Micronaut

Let's say I have a class called "WebSocketAdapter" annotated with #ServerWebSocket. This class has #OnOpen, #OnClose, #OnMessage functions similar to the chat example.
Inside my class I have a constructor that is passed in a WebSocketBroadcaster. Inside my socket functions I have a WebSocketSession which I can save out to the object if I want, but I am actually using the broadcaster to broadcast to all open sockets.
Next, I have an #Controller class with a #Post controller function. This just writes the posted data with println.
This may or may not be relevant: I am using an #Singleton with DefaultRouteBuilder to #Inject the POST controller dynamically.
Finally, I have my index.html set up as a static resource with a simple script built to consume websockets append data to the DOM.
So, I can stand up micronaut, visit localhost and see data stream in from my socket to the page. Also, I can post to my endpoint and see data in the console.
My question is how can I make my socket session broadcast when I post to the post controller? How exactly do I inject the websocket as a depenedency of the post controller so I can send the message posted to the server to all open browsers? Note: I am using Kotlin but open to any suggestion in any language.
Things I have tried:
Passing WebSocketSession directly into the post controller and hoping it
gets 'beaned' in
Trying to access the bean via
BeanContext.run().getBean(WebSocketAdapter::class.javaClass) and use it's broadcaster or session
Making the #ServerWebSocket a #Singleton and using #Inject on the
session and trying to access it
Trying to find bean using #ApplicationContext and use it's session
Using rx to pass data between the classes (I am familiar with RxSwift)
I seem to be getting an error like: Bean Context must support property resolution
The documentation says
The WebSocketSession is by default backed by an in-memory map. If you add the the session module you can however share sessions between the HTTP server and the WebSocket server.
I have added the session module to my .gradle however, how exactly do I share my sessions between ws:// and http:// with micronaut?
Unfortunately there doesn't seem to be an equivalent of SimpMessagingTemplate in Micronaut.
They way I got around this was to create an internal #WebSocketClient which allowed me to connect to server. The server recognises the connection as internal due to the way I authorise it and interprets messages on this socket as commands that are interpreted and executed.
It works, but SimpMessagingTemplate would be better.
This technique worked for me:
def sockServer = Application.ctx.getBean(MySocketServer)
sockServer.notifyListeners("you've been notified!")
In my case this code resides in an afterInsert() method in a GORM object in a micronaut server. Calls would come in to a controller and update a GORM object, and the changes are sent out to listener.

What is a Grails "transactional" service?

I'm reading the Grails docs on services which make numerous mention of transactions/transactionality, but without really defining what a transactional service method really is.
Given the nature of services, they frequently require transactional behaviour.
What exactly does this mean? Are transactional methods only those that use JPA/JDBC to communicate with a relational DB, or do they apply to anything covered by JTA?
Is there any reason why I just wouldn't make a service class #Transactional in case it evolves to some day use a transaction? In other words, are there performance concerns to making all service methods transactional?
Grails services are transactional by default - if you don't want a service to be transactional, you need to remove all #Transactional annotations (both Grails' #grails.transaction.Transactional and Spring's #org.springframework.transaction.annotation.Transactional) and add
static transactional = false
If you haven't disabled transactions with the transactional property and have no annotations, the service works the same as if it were annotated with Spring's annotation. That is, at runtime Spring creates a CGLIB proxy of your class and registers an instance of the proxy as the Spring bean, and it delegates to an instance of your actual class to do the database access and your business logic. This lets the proxy intercept all public method calls and start a new transaction, join an existing one, create a new one, etc.
The newer Grails annotation has all of the same settings as the Spring annotation, but it works a bit differently. Instead of triggering the creation of a single proxy, each method is rewritten by an AST transform during compilation, essentially creating a mini proxy for each method (this is obviously a simplification). This is better because the database access and transaction semantics are the same, but if you call one annotated method from another annotated with different settings, the different settings will be respected. But with a proxy, it's a direct call inside the delegate instance, and the proxy is bypassed. Since the proxy has all of the logic to create a new transaction or use other different settings, the two methods will use the first method's settings. With the Grails annotation every method works as expected.
There is a small performance hit involved for transactional methods, and this can accumulate if there are a lot of calls and/or a lot of traffic. Before your code runs, a transaction is started (assuming one isn't active) and to do this, a connection must be retrieved from the pool (DataSource) and configured to turn off autocommit, and make the various transaction settings (isolation, timeout, readonly, etc.) have to be made. But the Grails DataSource is actually a smart wrapper around the "real" one. It doesn't get a real JDBC Connection until you start a query, so all of the configuration settings are cached until then, and then "replayed" on the real connection. If the method doesn't do any database work (either because it never does, or because it exits early based on some condition before the db access code fires), then there's basically no database cost. But if it does, then things work as expected.
Don't rely on this DataSource proxying logic though - it's best to be explicit about which services are transactional and which aren't, and within each service which methods are transactional and which aren't. The best way to do this is by annotating methods as needed, or adding a single annotation at the class level if all methods use the same settings.
You can get more info in this talk I did about transactions in Grails.
First, if your performance concerns are due to the fact your services are transactional then you have reached nirvana. I say this because there are going to be plenty of other bottle necks in your application long before this is a major (or even minor) concern. So, don't fret about that.
Typically in Grails a transaction relates to the transactional state of a database connection or hibernate session. Though it could be anything managed by the JTA with the proper Spring configuration.
In simple terms, it's usually means (by default) a database transaction.

Looking for interceptors for grails service class

Is there any interceptor I can use to validate incoming requests to the Grails service classes/Endpoints?
I know interceptors for controllers but I want to do it for Service/endpoint.
This sounds like what you are looking for:
Intercepting Service Methods
In the link mentioned above(Kelly's reply), interceptor logic for Service has been added in BootStrap class. That might suffice in most of the cases but not all. In case you are using Quartz scheduler then job might get triggered even before BootStrap has made required modifications.
The best place to modify a service method would be via custom plugin. You can decorate service method in doWithApplicationContext or doWithDynamicMethod available in Plugin class. These methods are triggered at first and guarantee that changes made will be available to all other classes. Please refer Grails custom plugin documentation for more information.

Spring.NET, Quartz & Transactions

I've just run into a problem with a Quartz job that I'm invoking through Spring. My ExecuteInternal method had a [Transaction] attribute (because it does a load of DB calls) but when it runs, I get the 'No NHibernate session bound to thread' error.
Just wondering if that's because Spring.NET doesn't support the [Transaction] attribute in Quartz objects?
If not, that's fine... I can start a transaction manually, but wanted to check that it was the case, and not a silly error in my config somewhere.
[Update]
I figured it out actually. In the API docs, it says the preferable way to do this is use transactions on the service layer. My job was using DAOs to do its work, but my transactions are on my service layer, so I just called service methods from my job instead to do the same work (saving, updating records etc) since they already existed.
It also suggests that if you give the SchedulerFactoryObject a DbProvider, you can use transactions in the job itself, but when I did that it seemed to want to find my triggers configured in a special table in the DB (which I haven't set up since my triggers are all in XML) but that's possibly another way to do it.
Calling service methods works fine for me though.
The transaction attribute works using aop. Spring.NET creates an aop proxy for the decorated object. This proxy creates the session and starts the transaction.
In the ExecuteInternal method, you don't call the method on a proxy, but on the target itself. Therefore spring cannot intercept the call and do its transaction magic.
Your services are injected and therefore the transaction attribute works for them.
There's a good explanation in the spring docs on this subject: http://www.springframework.net/doc-latest/reference/html/transaction.html#tx-understandingimpl

NServicebus Message Handler Lifecycle in IOC StructureMap

What is the required IOC instance lifecycle I need to use in conjuction with a NServiceBus message handler if I want an instance per message handled.
PerRequest won't work, since given the numerous constructor dependenices and dependency graph I have, it gives me many instances when I require only one per Handle(MessageX msg) call. I can't or don't want to inject it directly into the message handler since it is required further down the object graph. E.g. inject IPersonService, depends on IPersonRepository, they can be per request (Default), but IPersonDBContext need to be per message call.
PerThread won't work since NServiceBus uses the same worker threads over and over.
Singleton, HttpContext, etc.. are obviously not applicable.
Has anyone came across this with either StructureMap or Castle?
I might be missing something here, but PerRequest will give you a new instance for each MessageHandler ( the messagehandlers are them selves registered as PerRequest). I have just committed a fix for a bug that caused messagehandlers to fire multiple times for each message. I wonder if that bug has been misleading you (try to get the lastest 2.0 build from CI and see if that does it for you)
http://teamcity.codebetter.com/viewLog.html?buildId=7087&tab=artifacts&buildTypeId=bt96
Hope this helps!

Resources