I created a simple JsonRPC server (Netty socketServer) to perform certain tasks common to our team, but called from different networks. The server receives a JSON-RPC request from the (Netty socket client) client, searches for a method, and calls the method using the parameters passed. The method itself is the one that returns the JSON-RPC response. How can I create an architecture that allows me to find the required method using a JSON-RPC request and execute it. Need to create a mapping. a photo

  • what have you already created? and what do you want to add to your creation? - Mikhail Vaysman
  • have you heard about reflection? - JVic

1 answer 1

In my perverted head came such a decision. I have no doubt that there are more "correct" and beautiful ways.

public class Handler { private Map<String, Controller> controllers; public Handler() { controllers = new HashMap<>(); //создаСм экзСмпляры ΠΊΠΎΠ½Ρ‚Ρ€ΠΎΠ»Π»Π΅Ρ€ΠΎΠ² Π½Π° Ρ€Π°Π·Π½Ρ‹Π΅ ΠΌΠ΅Ρ‚ΠΎΠ΄Ρ‹ controllers.put("hello", input -> { /*some code*/ return "{result...}"; }); controllers.put("ping", input -> "{\"result\": \"pong\"...}"); controllers.put("foo", input -> new FooController().execute(input)); } public String handle(String input) { //ΠΈΡ‰Π΅ΠΌ Π½ΡƒΠΆΠ½Ρ‹ΠΉ ΠΊΠΎΠ½Ρ‚Ρ€ΠΎΠ»Π»Π΅Ρ€ Controller controller = controllers.get(parseMethodName(input)); if (controller != null) return controller.execute(input); else //Π½Π΅ нашли - Π²ΠΎΠ·Π²Ρ€Π°Ρ‰Π°Π΅ΠΌ 404 ΠΈΠ»ΠΈ ΠΊΠΈΠ΄Π°Π΅ΠΌ ΠΈΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΠ΅ return "404"; } private String parseMethodName(String input) { //Ρ‚ΡƒΡ‚ ΠΌΠΎΠΆΠ½ΠΎ Ρ€Π°ΡΠΏΠ°Ρ€ΡΠΈΡ‚ΡŒ Π½Π°Π·Π²Π°Π½ΠΈΠ΅ ΠΌΠ΅Ρ‚ΠΎΠ΄Π° return "methodName"; } public class FooController implements Controller { @Override public String execute(String input) { return "bar"; } } public interface Controller { String execute(String input); } } 
  • Thank you. It was very helpful to me! - Mansur Kurtov