I'm using HK2 for my DI. The DI is injected as a Singleton.class.
This all works well, except I now have a use case that the DI needs to be updated. Imagine that I am injecting a List<SomeClass> using HK2. When the app boots, the List contains N elements.
At some future time, I have an internal API that I want this list to be updated if I hit. Right now, I have to reboot the app for the new List to show up.
How can I "refresh/update" the dependencies in HK2?
Related
That's one more attempt to make a dig at the theme "there is no order of OSGI bundles activation".
I have 4 services (bundles) which implement the same interface DataProvider meaning they implement it literally and also have it as service = { DataProvider.class } at their #Component annotations. This interface provides something like diagnostic data from these services. I want to collect this data from all 4 services and to print it on the GUI, which is also an OSGI bundle in my big framework. In order to do that I created such a reference in my GUI bundle:
#Reference
private volatile List<DataProvider> dataProvider;
and then I want to iterate over that list and append to the GUI's textframe everything I need.
The problem is that at the moment when GUI bundle starts, only two of four services are activated, so my list will contain only two service objects instead of all four and print only them. The last two services are loaded after my GUI Bundle has been already activated, because they also wait until their own references become fully satisfied (where some network operations are done, so it takes some time, around 10 seconds). Of course I want my GUI to show the diagnostic data from all 4 services. What could I do for that?
I tried to add policyOption = ReferencePolicyOption.GREEDY to the #Reference annotation, I expected it would force to reactivate GUI bundle each time this List<DataProvider> dataProvider receives a new member, but no, it didn't happen.
P.S. yes there is certainly a straightforward solution: just to add Thread.sleep() to the GUI Bundle with some appropriate value, so to the time of awakening the discussed above list will be full. But this is really bad thing, I don't want the user waits like 10 seconds before GUI appears, not to speak about the situations, when something goes wrong.
You can specify the minimum cardinality in the configuration. In your case, this is specified with the dataProvider.minimum.cardinality property in the configuration for your component. (See section 112.6.2.2 Minimum Cardinality Property.)
package com.example;
#Component
public class Diagnostics {
#Reference
List<DataProvider> dataProvider;
}
So then you need to add a configuration record for PID com.example.Diagnostics:
dataProvider.minimum.cardinality = 4
This model of using configuration works very well with the Configurator Specification. With this specification, you can specify the configuration of an application in a bundle.
Alternatively, you can create 4 references and distinguish the services by a property, using the target annotation method to specify a filter.
I am struggling a little bit to understand how to implement a Hystrix Metrics Publisher plugin.
Having read the documentation, it is still not clear how things are supposed to work together.
My goal is to write a plugin that will collect every metrics published by hystrix and write these metrics to a file on disk.
This file will later be collected and processed by an external tool giving us a good historical basis of the circuit’s behavior and problems.
The system where hystrix is running is a normal spring application. This said, I am also somewhat new on the java platform (although I am comfortable with the java language).
I thought that a first step towards understanding how the plugin could be implemented would be looking at the already implemented publishers. With this in mind, I looked at some of the implementations of hystrix-contrib directory.
I have chosen hystrix-codahale-metrics-publisher and hystrix-servo-metrics-publisher.
Both of them have a main class (servo is HystrixServoMetricsPublisher) which seems to register for receiving all possible kinds of metrics and some classes to deal with each kind of metric.
By looking at what I will call the main class, I see that, for example, there is a method called getMetricsPublisherForCommand that must return an implementation of the interface HystrixMetricsPublisherCommand.
Now questions start:
Question 1 I am assuming that once a plugin is registered every execution of every command on the context where the plugin is registered, and by the word command we can understand every execution of the execute() method of every class which inherits from HistrixCommand on that context, will generate a call to the getMetricsPublisherForCommand() method of my plugin. Is it true?
If so, there are a lot of low level implementations in hystrix such as thread pools and other, Should my getMetricsPublisherForCommand() implementation be thread-safe or I am guaranteed to receive calls in a sequential order? On what thread will my getMetricsPublisherForCommand() be executed?
Question 2 By looking at the documentation I am still not sure about what exactly the implementation of HystrixMetricsPublisherCommand to be returned by getMetricsPublisherForCommand() has to do. This is due to the fact that the HystrixMetricsPublisherCommand interface only specifies a method called initialize (). if it specified a method called, say, publish() I would conclude that the hystrix engine would call my custom getMetricsPublisherForCommand() method to get a metrics publisher on which it would call a publish() method to perform the custom publishing. But the initialize () method seens to be called only once when this given object is returned and I have found no other method the engine would call afterwards.
Also, by reading the documentation, I am under the impression that the implementation of HystrixMetricsPublisherCommand returned by getMetricsPublisherForCommand() will be somehow a singleton which completely breaks my understanding about how the thing is supposed to work.
The documentation say this:
The initialize() method will be called once-and-only-once to indicate when this instance can register with external services, start publishing metrics etc.
If you look at the servopublisher however you will notice that, unless I am completely and absolutely confused, the publishing stuff is performed right from the constructor. Now, if initialize() will be called to make some setup, how can I code my logic from the constructor where, unless the object is a singleton, it will be executed before any method including initialize () will have a chance to be called? In the other hand ,,, if this is a singleton, how can it run its constructor for every hystrix command?
May be I have missed something, I don't know ... but I need to understand conceptually what is going on here in order to implement my logic the right way. Thanks for your patience and I hope I have made myself clear enough in this long question.
First, recommend staying within the one (concise) question format.
Second, recommend using an existing implementation such as the default CodaHale (formerly DropWizard) implementation (which publishes to Graphite repository for Grafana consumption for example) to get it working.
HystrixPlugins.reset();
final WebApplicationContext springContext =
WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
HystrixPlugins plugins = HystrixPlugins.getInstance();
plugins.registerCommandExecutionHook(...);
// Good idea to use properties to enable/disable metrics generally...
// Using Spring type example...
if (hystrixMetricsEnabled.get()) {
plugins.registerMetricsPublisher(new HystrixCodaHaleMetricsPublisher(
getRegistry(springContext, sce.getServletContext())));
...
Otherwise the Hystrix documentation and full source of classes involved are publicly available:
https://github.com/Netflix/Hystrix/wiki/Plugins#metricspublisher
To explain the use case in as few words as possible, we have a set of controllers (and associated services) that we want to deprecate. In this same project we have introduced fancy new stuff to take its place. For the simplicity sake, all the same REST endpoints are implemented by both sets of work. The only difference being the first set of controllers are namespaced to /v1/ and the latter /v2/.
To verify that all this new work actually works in production, the goal was to incrementally push traffic in that direction. Whether it is "make 5% of the traffic go to the new stuff" or "for all calls dealing with orders from Factory X go to the new stuff" or some other piece of routing logic.
I'm trying not to touch the old code (that would require retesting all of it), so figured I could just hijack how Spring maps a request to a controller. Initially I thought I could I extend RequestMappingHandlerMapping and override the lookupHandlerMethod() call, but while that method is protected in the Abstract base class the very important map of handlerMethods and urlMap are private: leaving me in the lurch when it comes to providing a differing but existing handlerMethod.
I'd like to leverage as much as I can from the AbstractHandlerMethodMapping and the RequestMappingHandlerMapping classes. Currently, without access to the handler maps, I'm debating whether to completely use them, but change the lookupPath string and create my own HttpServerRequest class where I've edited the request URI to match my "new" controllers.
Any ideas? I'm hoping there is something I am missing.
I'm using Guice to route requests in my web app, and I'd like to modularize the routing of some of the URL patterns I'll be handling. Ideally, I'd like to be able to do something like this in my ServletModule:
delegate("/foo/bar/*").to(SomeOtherServletModule.class);
// in SomeOtherServletModule.configureServlets:
serve("/foo/bar/quux").with(Quux.class);
Or even better:
delegatePrefix("/foo/bar/").to(SomeOtherServletModule.class);
// in SomeOtherServletModule.configureServlets:
serve("/quux").with(Quux.class); // prefix removed
Is this possible in Guice? It seems that Guice tries really hard to make the bindings installed by ServletModules a singleton, which is in turn stored who-knows-where by GuiceServletContextListener to be used by GuiceFilter, but I'd like to un-singleton this so I can delegate like this, instead of having everything tightly bound in a single function.
I am the creator of Guice Servlet. This is basically not allowed as you are describing, as we felt it would be confusing for modules that are not intended to be used this way.
For example, many modules contribute filters that register at "/*" to provide some interception functionality (such as transactions). These could accidentally stop working if you auto-prefixed them. Given that servlet modules can be transitively installed, this is not as simple as being vigilant about one piece of code. Also, with regex bindings (example: /\.html$/), how does one handle prefixes? Do we support them (difficult problem)? Or do we simply register regex bindings normally and make a surprising exception for them?
Considering that what you're asking for is trivially achieved with a constructor in SomeOtherServletModule("/myprefix") that knows how to map itself correctly, we decided not to provide this functionality.
I am taking a look into Spring as a web framework, however I am needing a bit of help getting my head around DI.
The concept of objects getting constructed in the container on run time is such a new concept.
I am just wondering how this will reflect in a big application, would I have some modules doing work that are more highly coupled or should every object be initialised at runtime?
It all seems a little intensive to me, I mean say for example I have a CSV file data mining application that removes the data per row - each rows data is encapsulated in one of my own CSVRow objects for processing or whatever. These objects are instantiated whenever an Excel file maybe uploaded to the server. I don't know how many I will need to create?
I seem to be getting a bit lost, any clarity, an overview or some guidance would be much appreciated.
Thanks in advance!
I'll try to put it simply:
use dependency injection for stateless classes that have logic (business logic, persistence logic, front-end logic)
use new for value objects
Broadly speaking, an application is made up of a collection of classes that implement the business logic.
Normally each object is responsible to obtain references of the objects it needs (and this object's dependencies).
I think it is obvious that this leads to:
1) tightly coupled classes
2) code hard to test since each object instantiates specific classes it depends on and if there needs to be a change, the code must be modified.
So using Dependency Injections the objects do not instantiate the dependent objects themselves but an "external component" provides the dependencies at the object creation time i.e. injects the dependencies into the objects.
So in your example, the idea is that you can have for example a CsvRow object instantiated by Spring (along with all its dependencies) and get an object whenever needed. It is also possible to switch to for example CsvRow2 object (another implementation) by just changing your configuration
You don't need to use DI for your CSV row abstraction. Once you get the file, when you start parsing it, your code can create the CSVRow things as it goes. You don't need to wire them up.
You certainly could if you wanted to. You would grab your applicationContext and just get the beans by name. You would want to do this if the CsvRow had dependencies that you wanted Spring to manage for you.
I think of Spring as a way to create "singletons". When I want to guarantee there's only one instance of a class in the application, use Spring to create it. But, instead of being a traditional singleton with a static INSTANCE field or similar, it's a POJO with whatever constructors / setters you need. Spring creates the instance at runtime for you and makes sure that creation only happens once.