使用jsonrpc4j记录JSON-RPC调用

时间:2015-08-28 09:42:28

标签: java json jackson jsonrpc4j

我确信如果您使用过jsonrpc4j(弹簧容器外的 ),您将会识别以下标准模式。

public class MyServletJsonRpc extends HttpServlet {
   private MyService myService;
   private JsonRpcServer jsonRpcServer;

   @Override
   protected void doPost(HttpServletRequest request
                      , HttpServletResponse response) throws IOException {
      jsonRpcServer.handle(request, response);
   }
   @Override
   public void init(ServletConfig config) {
       myService = new MyServiceImpl();
       jsonRpcServer = new JsonRpcServer(myService, MyService.class);
       jsonRpcServer.set...
   }

我正在尝试创建一个包含所有JSON请求和JSON响应的日志文件。即,我想在反序列化之前记录传入的JSON RPC请求,并在序列化后立即记录该请求。

我一直在阅读代码,似乎没有一个简单的方法来做到这一点。有人可以帮忙吗?

我提出的解决方案(有效)使用了各种装饰,但我对此并不满意:

public class MyServletJsonRpc extends HttpServlet {
   private MyService myService;
   private JsonRpcServer jsonRpcServer;

   @Override
   protected void doPost(HttpServletRequest request
                      , HttpServletResponse response) throws IOException {
      jsonRpcServer.handle(request, response);
   }
   @Override
   public void init(ServletConfig config) {
       myService = new MyServiceImpl();
       ObjectMapper mapper = new MyObjectMapper(null, null, null);
       jsonRpcServer = new MyJsonRpcServer(mapper, myService, null);
       jsonRpcServer.set...
   }
}

使用以下2个重载类:

class MyObjectMapper extends ObjectMapper {
    private static final Logger L = LoggerFactory.getLogger(MyObjectMapper.class);

    public MyObjectMapper(JsonFactory jf, DefaultSerializerProvider sp, DefaultDeserializationContext dc) {
        super(jf, sp, dc);
    }

    @Override
    public void writeValue(OutputStream out, Object value) throws IOException, JsonGenerationException,
JsonMappingException {
        super.writeValue(out, value);
        L.info("Out: " + writeValueAsString(value));
    }

}

class MyJsonRpcServer extends JsonRpcServer {
    private static final Logger L = LoggerFactory.getLogger(MyJsonRpcServer.class);

    public MyJsonRpcServer(ObjectMapper mapper, Object handler, Class<?> remoteInterface) {
        super(mapper, handler, remoteInterface);
    }

    @Override
    public void handleNode(JsonNode node, OutputStream ops) throws IOException {
        L.info("In: " + (node == null ? "(null)" : node.toString()));
        super.handleNode(node, ops);
    }
}

我认为这看起来像是一个讨厌的黑客。有没有更好的方法呢?

1 个答案:

答案 0 :(得分:1)

图书馆支持使用InvocationListenerhttps://github.com/briandilley/jsonrpc4j/blob/master/src/main/java/com/googlecode/jsonrpc4j/InvocationListener.java

您可以在servlet init()方法中将其添加到服务器,所有调用都将通过它。

这里是二传手:https://github.com/briandilley/jsonrpc4j/blob/cfdaea92fedf7b43be9d93420df168fe69a5a4fa/src/main/java/com/googlecode/jsonrpc4j/JsonRpcBasicServer.java#L994

所以只需致电server.setInvocationListener,您就可以了。