Create Project Service

I've written a class that takes a PersistentStateComponent and creates a connection pool for making http requests in my plugin. I'd like to be able to use one instance of this class througout my entire project just like I do with my PersistentStateComponent with ServiceManager.getService. Is this possible? Right now I'm creating lots of instances of this class but I'd like to share one connection pool for the project. My code looks like this.

 
public class DWServerConnection {
    private final String basePath;
    private final
CloseableHttpClient client;
    private final
CredentialsProvider credentialsProvider;

    public
DWServerConnection(DWSettingsProvider settingsProvider) {
        String hostname = settingsProvider.getHostname();
        
String username = settingsProvider.getUsername();
        
String password = settingsProvider.getPassword();

        
credentialsProvider = new BasicCredentialsProvider();
        
credentialsProvider.setCredentials(
            new AuthScope(hostname, AuthScope.ANY_PORT),
            new
UsernamePasswordCredentials(username, password));

        
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        
connectionManager.setMaxTotal(200);
        
connectionManager.setDefaultMaxPerRoute(20);

        
client = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .build();
    
}

    public CloseableHttpClient getClient() {
        return client;
    
}
}
4 comments
Comment actions Permalink

Yes. Simply register the class as <projectService> in plugin.xml and use ServiceManager.getService(Project) to obtain its instances.

0
Comment actions Permalink

Ahhh that sounds easy enough. I have one more question about the constructor. Right now my service takes another service in the constructor, is the project passed to the constructor if I register it in the plugin xml? Or would I not take any arguments and put my service into a project component and use a start connection pool method then in project close use a shutdown connection pool method? Thanks for the help!

0
Comment actions Permalink

Yes, you can declare a project and any other project components or services as the parameters of your constructor, and the framework will pass you the correct instances.

0
Comment actions Permalink

Perfect! Thank you!

0

Please sign in to leave a comment.