How can use KeycloakSecurityContext in child thread - spring-boot

I have a problem with spring security context when I'm using asynchronous tasks. I use Keycloak for security and kafka for queue management. However, when kafka's listeners start, SpringAuditorAware loses the user's information (it's null). someone can help about how to propagate spring context in child thread using KeycloakSecurityContext
thanks

Related

Implement runnable to serve a new request in springboot

I have a usecase in a spring boot application, where in we get a request, we send an acknowledgement back and then start a new executor task in background which will do some processing and send back some result.
Now I am having some doubts while creating the runnable task. I want for every request a new instance of this runnable task is submitted to the executor service.
Could some clarify if keeping the scope as "prototype" should resolve my purpose or the scope should be "request". And if the latter is correct, is the default context in spring boot is web-aware?
Also I need to pass in some parameters in the runnable task. Any pointers would be appreciated for both the above problems.
TA
Spring can manage threads for you using the #Async annotation. This can be much simpler than managing them yourself if you are already using Spring.
You can read about it here: https://www.baeldung.com/spring-async

spring-boot graceful shutdown

Is there a way in spring boot to control the graceful shutdown of the app.
I know that you can have #PreDestroy methods in beans but how can you control the ordering in which those #PreDestroy methods are called.
You can have multiple beans depending on each other will the shutdown of the context look for this dependency already and call the #PreDestroy methods in the right order or not?
For example what I would like to accomplish is:
1.) stop listening for new requests on rest endpoints
2.) prevent rabbit message listeners to accept new messages
3.) wait for all processing that has started before the shutdown but is not finished yet.
Spring-boot-2-3-0 has added support for graceful shutdown.
you can enable graceful shutdown by setting up server.shutdown=graceful property
To configure the timeout period you can use
spring.lifecycle.timeout-per-shutdown-phase=20s
spring boot documentation
If you can not upgrade to spring boot 2.3 then you can check below project
https://github.com/gesellix/graceful-shutdown-spring-boot

Spring Session with hazelcast session events firing

I am using Spring Session with Hazelcast and Spring Websockets. As I don't need clustarization I use hazelcast with MapSessionRepository. But it doesn't fire event on session expiring or session deleting. What I want is to listen to SessionExpiredEvent and then disconnect user via websocket immediately. So I have two problems:
MapSessionRepository does not firing needed events (SessionExpiredEvent and etc.)
I don't realize how to send websocket notification using expired http session. I need something like simpMessageTemplate.convertAndSendToUser().
But how I can get the user?
So the only one variant I can see is to write own implementation for SessionRepository<ExpiringSession> with events firing. I hope you understood my question. Thanks in advance.
Spring Session Hazelcast support does provide publishing of session events. The functionality itself is implemented using SessionEntryListener so make sure you use #EnableHazelcastHttpSession annotation which configures all the necessary components for Hazelcast integration.
It might also be of your interest that the upcoming Spring Session 1.3 (currently at 1.3.0.M2) will provide first-class Hazelcast support with new HazelcastSessionRepository (which will, among other things, replace SessionEntryListener).

Initializing tables on spring boot startup

I have a spring boot application, in which I need to initialize the tables based on some configuration. I am using managed transactions using #Transactional. My problem is that I do not know when app is ready to make DB transactions.
I created a bean which reads the configuration and updates the tables, but it gets an exception at that point:
Could not obtain transaction-synchronized Session for current thread
I have tried that if I wait sprintboot to start and make the same transactions through HTTP requests, then there is no problem. So it seems to be a timing problem. I have also tried moving the code to #PostConstruct of bean but it does not fix the issue.
How can I know that app is ready for DB transactions? Any help will be much appreciated.
You can listen on some events Spring is publishing.
See here
You properbly need to listen on this even: ContextRefreshedEvent
The simplest and cleanest way of performing the initialization should be by making your bean implement ApplicationListener for ContextRefreshedEvent and then handling the initialization in the onApplicationEvent method. This way, your initialization will run when Spring's whole application context is initialized

how can we use addShutdownHook in project?

i saw some code use ShutdownHook like this
Runtime.getRuntime().addShutdownHook(new Thread(){
ConfigurableApplicationContext.stop();
//close spring context;
threadpool.shutdownnow();
//close theadpool
});
is there anything useful to do like this?
i thought
when jvm exit ,maybe thread will be shutdown immediately
and spring context will close tooï¼›
what shall we do next when we need to call System.exit() ?
It really depends on your application and the lifecycle of your objects and those threads you appear to have outside of your context. If you are running the spring container inside a standalone java process, then trapping the shutdown hook like this is one way to do that. Another way is to have it listen on a tcp port and send a command to begin the shutdown process. If you are running in a web container like tomcat, then you should follow the standards on normal webapp shutdown, which Spring supports with Context Listeners.
I would also consider redesigning your app so that the threads are all managed with a bean that lives inside your spring container. For instance using a bean that is configured with directives (attributes) for start/stop methods and then that bean would use an Executor for thread pooling. This way, your shutdown is ONLY shutting down the Spring container, and Spring provides very good support for orderly shutdown of beans. One of those beans is your object holding the threads within the Executor. Its a much cleaner way than trying to integrate Spring beans with external threads.
Hope this helps.

Resources