0

This is a structure question (what is best practice to use).

I have 50 Servlets for a domain site that I manage where the client makes js calls to java Servlet which in turn calls ElasticSearch and then servlet responds to client.

In each of my servlets immediately after the class name I create a static settings and client config for my ES connection. This is because in each servlet there may be 2 or more methods that call same ES cluster and I dont want to create this config in each method.

/**
 * Servlet implementation class Results
 */
@WebServlet("/Results")
public class Results extends HttpServlet {
    private static final long serialVersionUID = 1L;
    Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "elastictest").build();
    Client client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress("143.79.236.xxx", 9300));

HOWEVER, now Im wondering should I do that 50 times (1 config at top of each class)? Or do I create a single new java class with the same config and in each servlet reference that one new java class? Does that save memory and better practice?

**--Inside name.java --**

public static Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "elastictest").build();
public static Client client = new TransportClient(settings).addTransportAddress(new InetSocketTransportAddress("143.79.236.xxx", 9300));

--Inside ALL methods in 50 servlets reference name.client instead--

SearchResponse response = name.client.prepareSearch().setQuery(......

Also, at the bottom of my doPost (after I have sent out printWriter.println(results)) do I close the client? client.close();

Thank you.

1 Answer 1

1

I wouldn't store these objects on the class scope. I think it's better to open the client connection only at the beginning of your doPost, and close it at the end. In this way, the memory and network resources are only taken when necessary, and you don't have to take care about keeping a connection alive, keeping data in a good state.

Apart from that, if you want to avoid duplicating code in all your classes, just create a new class (kind of "helper", or "delegate", or name it whatever you like) that contains a method that does the connection job, and return the client. Again, without any class member, just everything in the method.

More generally, if you want some more theory, I suggest reading on stateless programming Advantages of stateless programming?

Sign up to request clarification or add additional context in comments.

1 Comment

That makes a lot of sense, I never thought that. Thank you! ^1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.